import { useParams } from "react-router-dom";
import React, { useState, useEffect } 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, getCachedData } from "../../slices/apiDataManager";
import ProjectRepository from "../../repositories/ProjectRepository";
import { ActivityeRepository } from "../../repositories/MastersRepository";

import "./ProjectDetails.css";
import {useEmployeesByProjectAllocated, useProjectDetails} from "../../hooks/useProjects";


const ProjectDetails = () => {
  let {projectId} = useParams();
  const {projects_Details,loading:projectLoading,error:ProjectError} = useProjectDetails(projectId)
 
  const [project, setProject] = useState(null);
  const [ projectDetails, setProjectDetails ] = useState( null );
  const [activities, setActivities] = useState(null);
  const [loading, setLoading] = useState(true);
  const [ error, setError ] = useState( "" );
  
  const fetchActivities = async () => {
  
      const activities_cache = getCachedData("activitiesMaster");

      if (!activities_cache) {
        ActivityeRepository.getActivities()
          .then((response) => {
            setActivities(response.data);
            cacheData("activitiesMaster", response.data);
          })
          .catch((error) => {
            setError("Failed to fetch data.");
          });
      
      } else {
        setActivities(activities_cache);
      }
  
  };

  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">
              {/* About User */}
              <AboutProject data={projectDetails}></AboutProject>
              {/* About User */}
            </div>
            <div className="col-xl-4 col-lg-5 col-md-5">
              {/* Profile Overview */}
              <ProjectOverview project={ project} />
              {/* 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}
            activityMaster={activities}
            onDataChange={handleDataChange}
          ></ProjectInfra>
        );
        break;
      }
      case "workplan": {
        return (
          <WorkPlan
            data={projectDetails}
            activityMaster={activities}
            onDataChange={handleDataChange}
          ></WorkPlan>
        );
        break;
      }
      case "activities": {
        return (
          <div className="row">
            <div className="col-lg-12 col-xl-12">
              <ActivityTimeline></ActivityTimeline>
            </div>
          </div>
        );
      }
    
      default:
        return  <div className="misc-wrapper">
        <h2 className="mb-2 mx-2">Coming Soon!</h2>
        <p className="mb-4 mx-2">We're currently working on this feature and will have it ready shortly.
        Thank you for your patience!</p>
        <div className="mt-4">
            <img
                src="../assets/img/illustrations/girl-doing-yoga-light.png"
                alt="girl-doing-yoga-light"
                aria-label="Girl doing yoga light"
                width="500"
                className="img-fluid"
                data-app-dark-img="illustrations/girl-doing-yoga-dark.png"
                data-app-light-img="illustrations/girl-doing-yoga-light.png" />
        </div>
    </div>;
    }
  };

  useEffect(() => {
    // fetchData();
    setProject( projects_Details )
    setProjectDetails(projects_Details)
    fetchActivities();
  }, [projects_Details]);

  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>}
        </div>
      
        <div className="row">
          <ProjectNav
            onPillClick={handlePillClick}
            activePill={activePill}
          ></ProjectNav>
        </div>

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

export default ProjectDetails;
