import React, { useState, useEffect, useCallback } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

import ProjectOverview from "../../components/Project/ProjectStatistics";
import AboutProject from "../../components/Project/AboutProject";
import ProjectNav from "../../components/Project/ProjectNav";
import Teams from "../../components/Project/Team/Teams";
import ProjectInfra from "../../components/Project/ProjectInfra";
import { SpinnerLoader } from "../../components/common/Loader";
import WorkPlan from "../../components/Project/WorkPlan";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useProjectDetails, useProjectName } from "../../hooks/useProjects";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import eventBus from "../../services/eventBus";
import ProjectProgressChart from "../../components/Dashboard/ProjectProgressChart";
import AttendanceOverview from "../../components/Dashboard/AttendanceOverview";
import { setProjectId } from "../../slices/localVariablesSlice";
import ProjectDocuments from "../../components/Project/ProjectDocuments";
import ProjectSetting from "../../components/Project/ProjectSetting";
import DirectoryPage from "../Directory/DirectoryPage";
import { useProjectAccess } from "../../hooks/useProjectAccess";

import "./ProjectDetails.css";
import ProjectOrganizations from "../../components/Project/ProjectOrganizations";
import ProjectStatistics from "../../components/Project/ProjectStatistics";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE, SELF_ATTENDANCE, TEAM_ATTENDANCE } from "../../utils/constants";

const ProjectDetails = () => {
  const projectId = useSelectedProject();
  const dispatch = useDispatch();

  const { projectNames } = useProjectName();
  const { projects_Details, loading: projectLoading, refetch } =
    useProjectDetails(projectId);

  const { canView, loading: permsLoading } = useProjectAccess(projectId);
  const canRegularize = useHasUserPermission(REGULARIZE_ATTENDANCE);
  const canTeamAttendance = useHasUserPermission(TEAM_ATTENDANCE);
  const canSelfAttendance = useHasUserPermission(SELF_ATTENDANCE);


  useEffect(() => {
    if (!projectId && projectNames.length > 0) {
      dispatch(setProjectId(projectNames[0].id));
    }
  }, [projectId, projectNames, dispatch]);

  const [activePill, setActivePill] = useState(
    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);
  };

  if (projectLoading || permsLoading || !projects_Details) {
    return (
      <div
        className="d-flex justify-content-center align-items-center"
        style={{ height: "80vh" }}
      >
        <SpinnerLoader />
      </div>
    );
  }

  const renderContent = () => {
    switch (activePill) {
      case "profile":
        return (
          <div className="row">
            <div className="col-lg-4 col-md-5 mt-2">
              <AboutProject />
              <div className="card"><ProjectStatistics project={projectId} /></div>
            </div>

            <div className="col-lg-8 col-md-7 mt-2">
              <ProjectProgressChart ShowAllProject="false" DefaultRange="1M" />
              {(canRegularize || canTeamAttendance || canSelfAttendance) && (
                <div className="mt-5">
                  <AttendanceOverview />
                </div>
              )}
            </div>
          </div>
        );
      case "teams":
        return <Teams />;
      case "infra":
        return <ProjectInfra data={projects_Details} onDataChange={refetch} />;
      case "workplan":
        return <WorkPlan data={projects_Details} onDataChange={refetch} />;
      case "directory":
        return <DirectoryPage IsPage={false} projectId={projects_Details.id} />;
      case "documents":
        return <ProjectDocuments />;
      case "setting":
        return <ProjectSetting />;
      case "organization":
        return <ProjectOrganizations />;
      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;
