import { useSelector, useDispatch } from "react-redux"; // Import useSelector
import React, { useState, useEffect, useCallback } from "react";

import ProjectOverview from "../../components/Project/ProjectOverview";
import AboutProject from "../../components/Project/AboutProject";
import ProjectNav from "../../components/Project/ProjectNav";
import Teams from "../../components/Project/Teams";
import ProjectInfra from "../../components/Project/ProjectInfra";
import Loader from "../../components/common/Loader";
import WorkPlan from "../../components/Project/WorkPlan";
import Breadcrumb from "../../components/common/Breadcrumb";
import {
  cacheData,
  clearCacheKey,
  getCachedData,
  useSelectedproject,
} from "../../slices/apiDataManager";
import "./ProjectDetails.css";
import {
  useProjectDetails,
} from "../../hooks/useProjects";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import Directory from "../Directory/Directory";
import eventBus from "../../services/eventBus";
import ProjectProgressChart from "../../components/Dashboard/ProjectProgressChart";
import { useProjectName } from "../../hooks/useProjects";
import AttendanceOverview from "../../components/Dashboard/AttendanceChart";
import { setProjectId } from "../../slices/localVariablesSlice";

const ProjectDetails = () => {

  const projectId = useSelectedproject()

  const { projectNames, fetchData } = useProjectName();
  const dispatch = useDispatch()

  useEffect(() => {
    if (projectId == null) {
      dispatch(setProjectId(projectNames[0]?.id));
    }
  }, [projectNames])

  const {
    projects_Details,
    loading: projectLoading,
    error: projectError,
    refetch,
  } = useProjectDetails(projectId);

  // const [activePill, setActivePill] = useState("profile");
  const [activePill, setActivePill] = useState(() => {
  return localStorage.getItem("lastActiveProjectTab") || "profile";
});

  const handler = useCallback(
    (msg) => {
      if (msg.keyword === "Update_Project" && projects_Details?.id === msg.response.id) {
        refetch();
      }
    },
    [projects_Details, refetch]
  );

  useEffect(() => {
    eventBus.on("project", handler);
    return () => eventBus.off("project", handler);
  }, [handler]);

 const handlePillClick = (pillKey) => {
  setActivePill(pillKey);
  localStorage.setItem("lastActiveProjectTab", pillKey); // ✅ Save to localStorage
};


  const renderContent = () => {
    if (projectLoading || !projects_Details) return <Loader />;

    switch (activePill) {
      case "profile":
        return (
          <>
            <div className="row">
              <div className="col-lg-4 col-md-5 mt-5">
                <AboutProject></AboutProject>
                <ProjectOverview project={projectId} />
              </div>
              <div className="col-lg-8 col-md-7 mt-5">
                <ProjectProgressChart ShowAllProject="false" DefaultRange="1M" />
                <div className="mt-5"> <AttendanceOverview  /></div>
               
              </div>
            </div>
          </>
        );

      case "teams":
        return (
          <div className="row">
            <div className="col-lg-12">
              <Teams />
            </div>
          </div>
        );

      case "infra":
        return (
          <ProjectInfra data={projects_Details} onDataChange={refetch} />
        );

      case "workplan":
        return (
          <WorkPlan data={projects_Details} onDataChange={refetch} />
        );

      case "directory":
        return (
          <div className="row mt-2">
            <Directory IsPage={false} prefernceContacts={projects_Details.id} />
          </div>
        );

      default:
        return <ComingSoonPage />;
    }
  };

  return (
    <div className="container-fluid">
      <Breadcrumb
        data={[
          { label: "Home", link: "/dashboard" },
          { label: "Projects", link: "/projects" },
          { label: projects_Details?.name || "Project", link: null },
        ]}
      />

      <div className="row">
        <ProjectNav onPillClick={handlePillClick} activePill={activePill} />
      </div>

      {renderContent()}
    </div>
  );
};

export default ProjectDetails;