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

export const useTaskList = (projectId, fromDate, ToDate) => {
  const [TaskList, setTaskList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchList = async () => {
    const taskList_cached = getCachedData("taskList");
    if (!taskList_cached || taskList_cached?.projectId !== projectId) {
      try {
        setLoading(true);
        const resp = await TasksRepository.getTaskList(
          projectId,
          fromDate,
          ToDate
        );
        setTaskList(resp.data);
        cacheData("taskList", { projectId: projectId, data: resp.data });
        setLoading(false);
      } catch (err) {
        setLoading(false);
        console.log(err);
        setError(err);
      }
    } else {
      setTaskList(taskList_cached.data);
    }
  };
  console.log(TaskList)
  useEffect(() => {
    if (projectId) {
      fetchList();
    }
  }, [projectId, fromDate, ToDate]);

  return { TaskList, loading, error, refetch:fetchList};
};
