import { useEffect,useState } from "react"
import {
    cacheData,
    getCachedData,
  } from "../slices/apiDataManager"
import ProjectRepository from "../repositories/ProjectRepository";


  
export const useProjects =()=>{

  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const fetchData = async () => {
      const projects_cache = getCachedData("projectslist");
     
      if (!projects_cache) {
        setLoading(true)   
        ProjectRepository.getProjectList()
        .then((response) => {
          setProjects(response.data);
         
          cacheData("projectslist", response.data);
          setLoading(false);
        })
        .catch((error) => {
          setLoading(false)
          console.error(error);
          setError("Failed to fetch data.");
        });
      
      } else {
        if (!projects.length) setProjects(projects_cache);
      }
  };
 
  useEffect(()=>{
    fetchData()

   },[])

  return  { projects,loading,error,refetch:fetchData}
  
}

export const useEmployeesByProjectAllocated = ( selectedProject ) =>
  {
    const [projectEmployees, setEmployeeList] = useState([]);
    const[loading,setLoading] = useState(true)
    const [projects, setProjects] = useState([]);
  
     const fetchData = async (projectid) => {
         try {
               let EmployeeByProject_Cache = getCachedData("empListByProjectAllocated")
            if(!EmployeeByProject_Cache || !EmployeeByProject_Cache.projectId === projectid) {
            
            let response = await  ProjectRepository.getProjectAllocation(projectid)
            setEmployeeList(response.data);
            cacheData("empListByProjectAllocated",{data:response.data,projectId:projectid});
            setLoading(false)
            }else{
                 setEmployeeList(EmployeeByProject_Cache.data)
                 setLoading(false)
           }
          
         
         } catch (err) {
           setError("Failed to fetch data.");
           setLoading(false)
         }
      };
 
  
    useEffect(()=>{
     if(selectedProject){
      fetchData(selectedProject);
     }
    },[selectedProject])
  
  
    return {projectEmployees,loading,projects}
}
  
export const useProjectDetails =(projectId)=>{
  
  const [projects_Details, setProject_Details] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

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

  return  { projects_Details,loading,error,refetch:fetchData}
  
}