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 [completion, setCompletion] = useState(0);
  const [profileData, setProfileData] = useState([]);
  const { apiURL, apiHeaderJson } = useContext(ConfigContext);
  const { project_id } = useParams();
  const mapRef = useRef(null);
  const [position, setPosition] = useState([19.8852069, 75.3496363]); // Default position

  // FETCH PROFILE SUMMARY
  const GetProfileSummary = async () => {
    try {
      const response = await axios.get(`${apiURL}api/projects/${project_id}`);
      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);
    }
  };

  // CALCULATE PROJECT COMPLETION %
  // 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;
  //   if (today > end) return 100;

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

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

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

      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);
    }
  };

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

  // MAP FLY TO POSITION
  useEffect(() => {
    try {
      mapRef.current.flyTo(position, mapRef.current.getZoom());
    } catch (error) { }
  }, [position]);

  // ANIMATE PROGRESS BAR
  useEffect(() => {
    let startTime = null;
    let reqId;

    const duration = 1000;
    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">
      {/* PROGRESS CARD */}
      <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-danger"
              role="progressbar"
              style={{ width: `${animatedCompletion}%` }}
              aria-valuenow={animatedCompletion}
              aria-valuemin={0}
              aria-valuemax={100}
            >
              <div className="label">{animatedCompletion}%</div>
            </div>
          </div>
        </div>
      </div>

      {/* MAIN CARD */}
      <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.</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`}
                  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>

          {/* DETAILS */}
          <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 fw-semibold">
                      {profileData?.profile_email}
                    </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>
                    <h6 className="fw-semibold">
                      {profileData?.profile_contact_number}
                    </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-whatsapp-line" />
                    </div>
                  </div>
                  <div className="flex-grow-1 overflow-hidden">
                    <p className="mb-1">WhatsApp</p>
                    <h6 className="fw-semibold">{profileData?.profile_whatsapp}</h6>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="row">
        <RecentActivity />
        <ProgressPieChart project_id={project_id} />
      </div>
    </div>
  );
};

export default ProjectSummary;
