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


export const useAllEmployees = () =>
{
  const [employeesList, setEmployeeList] = useState([]);
  const [ loading, setLoading ] = useState( false )
  const [ error, setError ] = useState() 
  
  const fetchData = async () =>
  
  {
      try
      {
        let EmployeeList_cached = getCachedData( "AllEmployees" )
        if ( ! EmployeeList_cached )
        {
          setLoading(true)
          const response = await EmployeeRepository.getAllEmployeeList();
          cacheData( "AllEmployees", response.data )
          setEmployeeList(response.data)
        } else
        {
          setEmployeeList( EmployeeList_cached )  
          setLoading(false)
        }   
      } catch ( error )
      {
          console.error(error);
        setError( "Failed to fetch data." ); 
        setLoading(false)
        
      }
  }
  

  useEffect( () =>
  {
    fetchData()
  }, [] )
  return {employeesList,loading,error}
}

export const useEmployees =(selectedProject)=>{

  const [employees, setEmployeeList] = useState([]);
  const[loading,setLoading] = useState(true)
  const [projects, setProjects] = useState([]);

   const fetchData = async (projectid) => {
       try {
             let EmployeeByProject_Cache = getCachedData("employeeListByProject")
          if(!EmployeeByProject_Cache || !EmployeeByProject_Cache.projectId === projectid) {
          
            EmployeeRepository.getEmployeeListByproject(projectid)
              .then((response) => {
                setEmployeeList(response);
                cacheData("employeeListByProject",{data:response,projectId:projectid});
              })
              .catch((error) => {
                setError("Failed to fetch data.");
              });
            
          }else{
               setEmployeeList(EmployeeByProject_Cache.data)
          
         }
         setLoading(false)
       
       } catch (err) {
         setError("Failed to fetch data.");
         setLoading(false)
       }
    };


  useEffect(()=>{
   if(selectedProject){
    fetchData(selectedProject);
   }
  },[selectedProject])


  return {employees,loading,projects,reCallAllEmployee}
}

export const useEmployeeRoles = (employeeId)=>{
  const [loading,setLoading] = useState(true)
  const[error, setError] =useState()
  const [employeeRoles,setEmployeeRoles] = useState([])
  const fetchData = async (employeeid) => {
    
    try {
      RolesRepository.getEmployeeRoles(employeeid)
        .then((response) => {
          setEmployeeRoles(response);
          cacheData("employeelist", response);
        })
        .catch((error) => {
          setError("Failed to fetch data.");
        });
    } catch (err) {
      setError("Failed to fetch data.");
    } finally {
      setLoading(false);
    }
 };


  useEffect( () =>
  {
    if ( employeeId )
    {
       fetchData(employeeId);
      
   }
},[employeeId])


return {employeeRoles,loading,error}
}


export const useEmployeesByProject=(projectId)=>{
  const [loading,setLoading] = useState(false)
  const[error, setError] =useState()
  const [employees,setEmployees] = useState([])

  const fetchData = async () => {
    const Employees_cache = getCachedData("employeeListByProject");
    if(!Employees_cache || Employees_cache.projectId !== projectId){
           
        setEmployees(true)
        ProjectRepository.getEmployeesByProject(projectId)
          .then( ( response ) =>
          {
          setEmployees(response.data);
          cacheData("employeeListByProject", { data: response.data, projectId })
          setLoading(false)
        })
        .catch((error) => {
          setError("Failed to fetch data.");
          setLoading(false)
        });
      
      }else{
        setEmployees(Employees_cache.data)
        setLoading(false)
      }
  };


 useEffect(()=>{
  fetchData(projectId);
},[projectId])

return {employees,loading,error,recallProjectEmplloyee:fetchData}

}



export const useEmployeesAllOrByProjectId = (projectId) => {
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = async () =>
  {
  
    if (projectId) {
      
      const Employees_cache = getCachedData("employeeListByProject");

      if (!Employees_cache || Employees_cache.projectId !== projectId) {
        setLoading(true);
        setError(null); 
        try {
          const response = await ProjectRepository.getEmployeesByProject(projectId);
          setEmployees(response.data);
          cacheData("employeeListByProject", { data: response.data, projectId });
          setLoading(false);
        } catch (err) {
          setError("Failed to fetch data.");
          setLoading(false);
        }
      } else {
        setEmployees(Employees_cache.data);
        setLoading(false);
      }
    } else {
      
      const employeesCache = getCachedData("allEmployeeList");

      if (!employeesCache) {
        setLoading(true);
        setError(null);

        try {
          const response = await EmployeeRepository.getAllEmployeeList();
          setEmployees(response.data);
          cacheData("allEmployeeList", { data: response.data });
          setLoading(false);
        } catch (err) {
          setError("Failed to fetch data.");
          setLoading(false);
        }
      } else {
        setEmployees(employeesCache.data);
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    fetchData(); // Fetch data when the component mounts or projectId changes
  }, [projectId]); // Re-fetch when projectId changes

  return {
    employees,
    loading,
    error,
    recallEmployeeData: fetchData,
  };
};





export const useEmployeeProfile =(employeeId)=>{
  const [loading,setLoading] = useState(true)
  const[error, setError] =useState()
  const [employee,setEmployees] = useState()

  const fetchData = async () => {
    const Employee_cache = getCachedData("employeeProfile");
    if(!Employee_cache || Employee_cache.employeeId !== employeeId){
           
     
        EmployeeRepository.getEmployeeProfile(employeeId)
        .then((response) => {
          setEmployees(response.data);
          cacheData("employeeProfile", { data: response.data, employeeId })
          setLoading(false)
        })
        .catch((error) => {
          setError("Failed to fetch data.");
          setLoading(false)
        });
      
      }else{
        setEmployees(Employee_cache.data)
        setLoading(false)
      }
 };

 useEffect(()=>{
  fetchData(employeeId);
},[employeeId])

return {employee,loading,error}

}