import React, { useEffect, useState, useContext } from "react";
import axios from "axios";
import { calculateProgress, DateFormaterMonth } from "../../Components/GlobalFunctions"; // Update path if needed
import { ConfigContext } from "../../Context/ConfigContext";
import { ContentLoader } from "../../Components/Shimmer";

const EChartsBarChart = () => {
    const [projectProgress, setProjectProgress] = useState([]);
    const [loadingList, setLoadingList] = useState(false)
    const { apiURL, apiHeaderJson, user_profile_id } = useContext(ConfigContext);

    useEffect(() => {
        getAllProjectData();
    }, [apiURL, apiHeaderJson, user_profile_id]);

    const getAllProjectData = async () => {
        try {
            setLoadingList(true)
            const headers = apiHeaderJson;
            const response = await axios.get(
                `${apiURL}api/GetDashboard`,
                {
                    params: { contractor_id: user_profile_id },
                    headers
                }
            );
            setLoadingList(false)
            const totalProjects = response.data?.data?.tabs?.total_projects || [];

            const progressData = totalProjects.map((project) => {
                // Calculate time-based progress
                const timeProgress = calculateProgress(
                    project.project_start_date,
                    project.project_end_date
                ).progressPercentage;

                // Get actual completion percentage from API if available
                // Fall back to time-based if not available
                const actualProgress = project.completion_percentage || timeProgress;

                return {
                    id: project.project_id, // Better to use ID than index for key
                    name: project.project_title,
                    progressPercentage: Math.min(100, Math.max(0, actualProgress)), // Ensure between 0-100
                    startDate: DateFormaterMonth(project.project_start_date),
                    endDate: DateFormaterMonth(project.project_end_date),
                };
            });

            setProjectProgress(progressData);
        } catch (error) {
            console.error("Error fetching project data:", error);
        }
        finally {
            setLoadingList(false)
        }
    };
    return (
        <div className="card" style={{ height: "85vh" }}>
            <div className="card-header align-items-center d-flex">
                <h4 className="card-title mb-0 flex-grow-1">Project Progress</h4>
            </div>
            {
                loadingList ? <ContentLoader /> :
                    <>
                        <div className="card-body" style={{
                            padding: "20px",
                            height: "calc(85vh - 85px)",
                            overflowY: "auto"
                        }}>
                            {projectProgress.length > 0 ? (
                                projectProgress.map((project) => (
                                    <div key={project.id} style={{ marginBottom: "16px" }}>
                                        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "8px" }}>
                                            <span style={{ fontWeight: "bold" }}>{project.name}</span>
                                        </div>
                                        <div
                                            style={{
                                                background: "#e9ecef",
                                                width: "100%",
                                                height: "20px",
                                                borderRadius: "8px",
                                                overflow: "hidden",
                                            }}
                                        >
                                            <div
                                                style={{
                                                    background: project.progressPercentage >= 100 ? "#28a745" : "#3F7D58",
                                                    width: `${project.progressPercentage}%`,
                                                    height: "100%",
                                                    transition: "width 0.3s ease",
                                                }}
                                                title={`${project.progressPercentage}% complete`}
                                            ></div>
                                        </div>
                                        <div style={{ display: "flex", justifyContent: "space-between", marginTop: "4px" }}>
                                            <span style={{ fontSize: "12px" }}>
                                                {project.startDate} - {project.endDate}
                                            </span>
                                            <span style={{ fontSize: "12px", fontWeight: "bold" }}>
                                                {project.progressPercentage}%
                                            </span>
                                        </div>
                                    </div>
                                ))
                            ) : (
                                <div style={{ textAlign: "center", padding: "20px", color: "#666" }}>
                                    No projects found
                                </div>
                            )}
                        </div>
                    </>
            }
        </div>
    );
};

export default EChartsBarChart;