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";

const ProjectDetails = () => {
  let { projectId } = useParams();
  const {
    projects_Details,
    loading: projectLoading,
    error: ProjectError,
  } = 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">
              {/* About User */}
              <AboutProject data={projectDetails}></AboutProject>
              {/* About User */}
            </div>
            <div className="col-xl-4 col-lg-5 col-md-5  mt-5">
              {/* Profile Overview */}
              <ProjectOverview project={projectId} />
              {/* Profile Overview */}
            </div>
          </div>
        );
      }
      case "teams": {
        return (
          <div className="row">
            <div className="col-lg-12 col-xl-12">
              {/* Teams */}
              <Teams project={projectDetails}></Teams>
              {/* Teams */}
            </div>
          </div>
        );
        break;
      }
      case "infra": {
        return (
          <ProjectInfra
            data={projectDetails}
            onDataChange={handleDataChange}
          ></ProjectInfra>
        );
        break;
      }
      case "workplan": {
        return (
          <WorkPlan
            data={projectDetails}
            onDataChange={handleDataChange}
          ></WorkPlan>
        );
        break;
      }
      case "directory": {
        return (
          <div className="row">
            <Directory IsPage={false} prefernceContacts={projectDetails.id} />
          </div>
        );
      }

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

  useEffect(() => {
    dispatch(setProjectId(projectId));
    setProject(projects_Details);
    setProjectDetails(projects_Details);
  }, [projects_Details, projectId]);

  const handler = useCallback(
    (msg) => {
      if (msg.keyword === "Update_Project" && project.id === msg.response.id) {
        clearCacheKey("projectInfo")
        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);
        });
      }
    },
    [project,handleDataChange]
  );
  useEffect(() => {
    eventBus.on("project", handler);
    return () => eventBus.off("project", handler);
  }, [handler]);

  return (
    <>
      {}
      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Projects", link: "/projects" },
            { label: "Details", 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;
