import {useState,useEffect} from "react"
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData,getCachedData } from "../../slices/apiDataManager";
import { useSelector } from "react-redux";







export const useFeatures = () =>
  useMasterData("masterFeatures", MasterRespository.getFeatures);

export const useMasterRole = () =>
  useMasterData("masterRole", MasterRespository.getRoles);


const useMaster = () => {

  const selectedMaster = useSelector((store)=>store.localVariables.selectedMaster);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  useEffect(() => {
    const fetchData = async () => {
      if (!selectedMaster) return;
      setLoading(true);
      try {
        const cachedData = getCachedData(selectedMaster);
        if (cachedData) {
          
          setData(cachedData);
          
        } else {
          let response;
          switch (selectedMaster) {
            case "Role":
              response = await MasterRespository.getRoles();
              response = response.data;
              break;
            case "Job Role":
              response = await MasterRespository.getJobRole();
              response = response.data
                break;
            case "Module":
              response = [{description: null,module:"Module 1",featurePermission: null,id: "08dd4761-363c-49ed-8851-3d2489a3e98d"},{description: null,module:"Module 2",featurePermission: null,id: "08dy9761-363c-49ed-8851-3d2489a3e98d"},{description: null,module:"Module 3",featurePermission: null,id: "08dy7761-263c-49ed-8851-3d2489a3e98d"}];
              break;
            case "Status":
              response = [{description: null,featurePermission: null,id: "02dd4761-363c-49ed-8851-3d2489a3e98d",status:"status 1"},{description: null,featurePermission: null,id: "03dy9761-363c-49ed-8851-3d2489a3e98d",status:"status 2"},{description: null,featurePermission: null,id: "03dy7761-263c-49ed-8851-3d2489a3e98d",status:"Status 3"}];
              break;
            default:
              response = [];
          }

          if (response) {
            setData(response);
            cacheData(selectedMaster, response);
          }
        }
      } catch (err) {
        setError("Failed to fetch data.");
      } finally {
        setLoading(false);
      }
    };

    if ( selectedMaster )
    {
     
      fetchData();
    }
    
  }, [selectedMaster]);

  

  return { data, loading, error }
};




export default useMaster;

