import { useEffect, useState } from "react";
import { TasksRepository } from "../repositories/TaskRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import {MasterRespository} from "../repositories/MastersRepository";
// 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 (projectId, dateFrom, toDate) => {
    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);
    }
  
  }, [projectId, dateFrom, toDate]);

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


export const useTaskById = (TaskId) =>
{
  const [Task, setTask] = useState([]);
  const [loading, setLoading] = useState(false);
  const [ error, setError ] = useState( null );
  


  const fetchTask = async(TaskId) =>
  {
    try
    {
      let res = await TasksRepository.getTaskById( TaskId );
      setTask( res.data );
      
    } catch ( error )
    {
      setError(err)
    }
  }
  useEffect( () =>
  {
    if ( TaskId )
    {
      fetchTask(TaskId)
    }
  }, [ TaskId ] )
  return { Task,loading}
}

export const useAuditStatus = () =>
{
  const [ status, setStatus ] = useState( [] );
  const [ error, setError ] = useState( '' );
  const [ loading, setLoading ] = useState( false )
  
  const fetchStatus = async() =>
  {
    try
    {
      const res = await MasterRespository.getAuditStatus()
      setStatus( res.data )
      cacheData("AuditStatus",res.data)
    } catch ( err )
    {
      setError(err)
    }
  }
useEffect(() => {
  const cache_status = getCachedData('AuditStatus');
  if (cache_status) {
    setStatus(cache_status);
  } else {
    fetchStatus();
  }
}, []);

  return {status,error,loading}
}