import { useParams } from "react-router-dom";
import React, { useState, useEffect, useCallback } from "react";

import ActivityTimeline from "../../components/Project/ActivityTimeline";
import ProjectOverview from "../../components/Project/ProjectOverview";
import AboutProject from "../../components/Project/AboutProject";
import ProjectNav from "../../components/Project/ProjectNav";
import ProjectBanner from "../../components/Project/ProjectBanner";
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,
} from "../../slices/apiDataManager";
import ProjectRepository from "../../repositories/ProjectRepository";
import { ActivityeRepository } from "../../repositories/MastersRepository";
import "./ProjectDetails.css";
import {
  useEmployeesByProjectAllocated,
  useProjectDetails,
} from "../../hooks/useProjects";
import { useDispatch } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import Directory from "../Directory/Directory";
import eventBus from "../../services/eventBus";
import ProjectProgressChart from "../../components/Dashboard/ProjectProgressChart";

const ProjectDetails = () => {
  let { projectId } = useParams();
  const {
    projects_Details,
    loading: projectLoading,
    error: ProjectError,
    refetch
  } = useProjectDetails(projectId);
  const dispatch = useDispatch();
  const [project, setProject] = useState(null);
  // const [projectDetails, setProjectDetails] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  // const fetchData = async () => {
  //   const project_cache = getCachedData("projectInfo");
  //   if (!project_cache || project_cache?.projectId !== projectId) {
  //     ProjectRepository.getProjectByprojectId(projectId)
  //       .then((response) => {
  //         setProjectDetails(response.data);
  //         setProject(response.data);
  //         cacheData("projectInfo", { projectId, data: response.data });
  //         setLoading(false);
  //       })
  //       .catch((error) => {
  //         console.error(error);
  //         setError("Failed to fetch data.");
  //         setLoading(false);
  //       });
  //   } else {
  //     setProjectDetails(project_cache.data);
  //     setProject(project_cache.data);
  //     setLoading(false);
  //   }
  // };

  const [activePill, setActivePill] = useState("profile");

  const handlePillClick = (pillKey) => {
    setActivePill(pillKey);
  };

  const handleDataChange = (data) => {
    fetchData();
  };

  const renderContent = () => {
    if (projectLoading) return <Loader></Loader>;
    switch (activePill) {
      case "profile": {
        return (
          <div className="row">
            <div className="col-xl-4 col-lg-5 col-md-5 mt-5">
              <AboutProject ></AboutProject>
            </div>
            <div className="col-xl-4 col-lg-5 col-md-5  mt-5">
              <ProjectOverview project={projectId} />
            </div>
          </div>
        );
      }
      case "teams": {
        return (
          <div className="row">
            <div className="col-lg-12 col-xl-12">
              {/* Teams */}
              <Teams ></Teams>
              {/* Teams */}
            </div>
          </div>
        );
        break;
      }
      case "infra": {
        return (
          <ProjectInfra
            data={projects_Details}
            onDataChange={handleDataChange}
          ></ProjectInfra>
        );
        break;
      }
      case "workplan": {
        return (
          <WorkPlan
            data={projects_Details}
            onDataChange={handleDataChange}
          ></WorkPlan>
        );
        break;
      }
      case "directory": {
        return (
          <div className="row">
            <Directory IsPage={false} prefernceContacts={projects_Details.id} />
          </div>
        );
      }

      default:
        return <ComingSoonPage></ComingSoonPage>;
    }
  };

  useEffect(() => {
    dispatch(setProjectId(projectId));

  }, [projects_Details, projectId]);

  const handler = useCallback(
    (msg) => {
      if (msg.keyword === "Update_Project" && projects_Details.id === msg.response.id) {
         refetch()
      }
    },
    [projects_Details, handleDataChange]
  );
  useEffect(() => {
    eventBus.on("project", handler);
    return () => eventBus.off("project", handler);
  }, [handler]);

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

        <div className="row">
          {projectLoading && <p>Loading....</p>}
          {/* {!projectLoading && project && (
            <ProjectBanner project_data={project}></ProjectBanner>
          )} */}

          <ProjectNav
            onPillClick={handlePillClick}
            activePill={activePill}
          ></ProjectNav>
        </div>

        <div className="row"></div>

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

export default ProjectDetails;
