import { getAllCartItems } from "@/store/cart";
import { getAllFavItems } from "@/store/fav";
import { setCategories, setLoader, setSettings } from "@/store/general";
import { AppDispatch, RootState } from "@/store/store";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import toast from "react-hot-toast";
import axiosInstance from "@/services/axiosClient";
import { setLocation } from "@/store/locationSlice";
import {deleteAuthedUserData,getAuthedUserData,getWallet} from "@/store/profile";
import { getAllAddressesItems } from "@/store/address";

const ApisCaller = ({settings,categories}:{settings:any,categories:any}) => {
  const dispatch = useDispatch<AppDispatch>();
  const { token } = useSelector((state: RootState) => state.ProfileConfig);


  useEffect(()=>{
      dispatch(setSettings(settings))
  },[settings])

  useEffect(()=>{
    if(categories){
      dispatch(setCategories(categories))
    }
  },[categories])

  const fetchAddressData = async () => {
    try {
      const response = await axiosInstance.get("locations");
      const location =
        response?.data?.data?.length > 0 &&
        response?.data?.data?.filter((ele: any) => ele.is_default == true);
      if (location?.length > 0) {
        dispatch(
          setLocation({
            lat: location[0].lat,
            lng: location[0].lng,
            location_description: location[0].location,
            id: location[0].id,
          })
        );
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
    } finally {
    }
  };


  useEffect(() => {
    if (token) {
      fetchAddressData();
      dispatch(getWallet());
      dispatch(getAuthedUserData());
      dispatch(getAllAddressesItems());
    } else {
      dispatch(deleteAuthedUserData());
    }
    dispatch(getAllFavItems());
    dispatch(getAllCartItems());
  }, [token]);

  return null;
};

export default ApisCaller;
