import { useEffect, useState } from "react";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import ProjectRepository from "../repositories/ProjectRepository";
import { useProfile } from "./useProfile";
import { useDispatch } from "react-redux";
import { setProjectId } from "../slices/localVariablesSlice";

export const useProjects = () => {
  const { profile } = useProfile();
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const fetchData = async () => {
    const projectIds = profile?.projects || [];

    const filterProjects = (projectsList) => {
      return projectsList
        .filter((proj) => projectIds.includes(String(proj.id)))
        .sort((a, b) => a.name.localeCompare(b.name));
    };

    const projects_cache = getCachedData("projectslist");

    if (!projects_cache) {
      setLoading(true);
      try {
        const response = await ProjectRepository.getProjectList();
        const allProjects = response.data;
        const filtered = filterProjects(allProjects);
        setProjects(filtered);
        cacheData("projectslist", allProjects);
      } catch (err) {
        setError("Failed to fetch data.");
      } finally {
        setLoading(false);
      }
    } else {
      if (!projects.length) {
        const filtered = filterProjects(projects_cache);
        setProjects(filtered);
        setLoading(false);
      }
    }
  };

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

  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 { profile } = useProfile();
  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: 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 (profile && projectId != undefined) {
      fetchData();
    }
  }, [projectId, profile]);

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