import axios from "axios";
import React, { useContext, useEffect, useRef, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { ConfigContext } from "../../Context/ConfigContext";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import RecentActivity from "../RecentActivity";
import ProgressPieChart from "../ProgressPieChart";

// Fix for default marker icon in Leaflet
const markerIcon = new L.Icon({
  iconUrl: require("leaflet/dist/images/marker-icon.png"),
  iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
  shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});

const ProjectSummary = () => {
  const [animatedCompletion, setAnimatedCompletion] = useState(0);
  const [profileData, setProfileData] = useState(null);
  const [completion, setCompletion] = useState(0);
  const { apiURL, apiHeaderJson } = useContext(ConfigContext);
  const { projectId } = useParams();
  const mapRef = useRef(null);
  const [position, setPosition] = useState([19.8852069, 75.3496363]); // Default position

  const GetProfileSummary = async () => {
    try {
      const headers = apiHeaderJson;
      const response = await axios.get(`${apiURL}api/projects/${projectId}`);
      const { data, success } = response.data;
      if (success) {
        setProfileData(data);
        if (data.project_latlng) {
          const [lat, lng] = data.project_latlng.split(",").map(Number);
          setPosition([lat, lng]);
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  const GetUsageProgress = async () => {
    try {
      const response = await axios.get(`${apiURL}api/project/information`, {
        headers: apiHeaderJson,
        params: { project_id: projectId }
      });

      const { success, data } = response.data;

      if (success) {
        const used = data?.progress?.TotalUsed || 0;
        const remaining = data?.progress?.TotalWork || 0;

        const total = used + remaining;

        // avoid divide by zero
        const percentage =
          total === 0 ? 0 : Math.round((used / total) * 100);

        setCompletion(percentage); // ← progress bar now uses THIS
      }
    } catch (error) {
      console.log("Error fetching usage progress", error);
    }
  };

  // const getProjectCompletionPercentage = (project) => {
  //   if (!project?.project_start_date || !project?.project_end_date) {
  //     return 0;
  //   }

  //   const start = new Date(project.project_start_date);
  //   const end = new Date(project.project_end_date);
  //   const today = new Date();
  //   today.setHours(0, 0, 0, 0);


  //   if (today < start) {
  //     return 0; // project not yet started
  //   }

  //   if (today > end) {
  //     return 100; // project finished
  //   }

  //   const totalDuration = end - start;
  //   const elapsedDuration = today - start;

  //   const percentage = (elapsedDuration / totalDuration) * 100;
  //   return Math.min(Math.max(Math.round(percentage), 0), 100);
  // };


  useEffect(() => {
    GetUsageProgress()
    GetProfileSummary();
  }, []);

  useEffect(() => {
    try {
      if (mapRef.current) {
        mapRef.current.flyTo(position, mapRef.current.getZoom());
      }
    } catch (error) { }
  }, [position, mapRef]);

  useEffect(() => {
    let startTime = null;
    let reqId;

    const duration = 1000; // total animation duration (ms)
    const startValue = 0;

    const animate = (timestamp) => {
      if (!startTime) startTime = timestamp;
      const elapsed = timestamp - startTime;

      const progress = Math.min(elapsed / duration, 1);
      const currentValue = Math.round(progress * completion);

      setAnimatedCompletion(currentValue);

      if (progress < 1) {
        reqId = requestAnimationFrame(animate);
      }
    };

    if (completion > 0) {
      reqId = requestAnimationFrame(animate);
    } else {
      setAnimatedCompletion(0);
    }

    return () => cancelAnimationFrame(reqId);
  }, [completion]);

  return (
    <div className="col-xxl-12">
      <div className="card">
        <div className="card-body">
          <h5 className="card-title mb-5">Project Completion</h5>
          <div className="progress animated-progress custom-progress progress-label">
            <div
              className="progress-bar bg-success"
              role="progressbar"
              style={{ width: `${animatedCompletion}%` }}
              aria-valuenow={animatedCompletion}
              aria-valuemin={0}
              aria-valuemax={100}
            >
              <div className="label">{animatedCompletion}%</div>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="row">
          <div
            className="col-md-4 d-flex justify-content-center align-items-center"
            style={{ borderRight: "2px dashed #c7c7c7" }}
          >
            <div className="ms-4 mt-3 ml-3 mb-4" style={{ zIndex: "0" }}>
              <MapContainer
                center={position}
                zoom={18}
                style={{ height: "200px", width: "300px" }}
                ref={mapRef}
              >
                <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
                <Marker position={position} icon={markerIcon}>
                  <Popup>
                    Project Location. <br /> Easily customizable.
                  </Popup>
                </Marker>
              </MapContainer>
              <div className="d-flex justify-content-center">
                <Link
                  to={`https://www.google.com/maps/@${position[0]},${position[1]},627m/data=!3m1!1e3?entry=ttu`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <button
                    type="button"
                    className="btn btn-primary btn-label waves-effect waves-light rounded-pill mt-3"
                  >
                    <i className="ri-map-pin-line label-icon align-middle rounded-pill fs-16 me-2" />{" "}
                    Get Direction
                  </button>
                </Link>
              </div>
            </div>
          </div>

          <div className="col-md-8">
            <div className="card-body">
              <div className="card-header bg-light bg-gradient">
                <h6 className="card-title mb-0 text-start">Project Summary</h6>
              </div>
              <div className="table-responsive mt-2">
                <p>{profileData?.project_description}</p>
              </div>
            </div>

            <div className="row mb-3">
              <div className="col-6 col-md-4">
                <div className="d-flex">
                  <div className="flex-shrink-0 avatar-xs align-self-center me-3">
                    <div className="avatar-title bg-light rounded-circle fs-16 text-primary">
                      <i className="ri-mail-fill" />
                    </div>
                  </div>
                  <div className="flex-grow-1">
                    <p className="mb-1">Email</p>
                    <h6 className="text-truncate mb-0">
                      <a href="#" className="fw-semibold">
                        {profileData?.profile_email}
                      </a>
                    </h6>
                  </div>
                </div>
              </div>

              <div className="col-6 col-md-4">
                <div className="d-flex">
                  <div className="flex-shrink-0 avatar-xs align-self-center me-3">
                    <div className="avatar-title bg-light rounded-circle fs-16 text-primary">
                      <i className="ri-phone-line" />
                    </div>
                  </div>
                  <div className="flex-grow-1 overflow-hidden">
                    <p className="mb-1">Contact Number</p>
                    <a href="#" className="fw-semibold">
                      {profileData?.profile_contact_number}
                    </a>
                  </div>
                </div>
              </div>

              <div className="col-6 col-md-4">
                <div className="d-flex">
                  <div className="flex-shrink-0 avatar-xs align-self-center me-3">
                    <div className="avatar-title bg-light rounded-circle fs-16 text-primary">
                      <i className="ri-whatsapp-line" />
                    </div>
                  </div>
                  <div className="flex-grow-1 overflow-hidden">
                    <p className="mb-1">WhatsApp</p>
                    <a href="#" className="fw-semibold">
                      {profileData?.profile_whatsapp}
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="row">
        <RecentActivity />
        <div className="col-md-4">
          <div className="card">
            <div className="card-header">
              <h5>Progress Overview</h5>
            </div>
            <div className="card-body p-0">
              <ProgressPieChart project_id={projectId} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProjectSummary;
