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

export const useTaskList = (projectId, dateFrom, 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,
          dateFrom,
          toDate
        );
        setTaskList(resp.data);
        cacheData("taskList", { projectId: projectId, data: resp.data });
        setLoading(false);
      } catch (err) {
        setLoading(false);
        setError(err);
      }
    // } else {
    //   setTaskList(taskList_cached.data);
    // }
  };
  useEffect( () =>
  {

    if (projectId && dateFrom && toDate) {
      fetchList();
    }
  
  }, [projectId, dateFrom, toDate]);

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