"use client";
import { useEffect } from "react";
import Cookies from "js-cookie";
import { useDispatch, useSelector } from "react-redux";
import { setLocation } from "@/store/locationSlice";
import { RootState } from "@/store/store";
import { useRouter } from "next/navigation";

import toast from "react-hot-toast";
import { useLocale } from "next-intl";

const LocationHandler = () => {
  const dispatch = useDispatch();
  const router = useRouter();
  const local = useLocale();

  useEffect(() => {
    const clientLocation = Cookies.get("client_location");
    const googleAPIKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;

    const fetchLocation = async (lat: number, lng: number) => {
      try {
        const response = await fetch(
          `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false&key=${googleAPIKey}&language=${local}`
        );
        const data = await response.json();

        if (data.results.length) {
          const addressComponents = data.results[0]?.address_components;
          const trimmedResults = addressComponents.slice(0, -2);
          const address = trimmedResults
            .map((el: any) => el.short_name)
            .join(" ");

          const locationData = {
            lat,
            lng,
            location_description: address,
          };
          dispatch(setLocation({ ...locationData, isLoading: false }));
          router.refresh();
        }
      } catch (error) {
        console.error("Error fetching geolocation address:", error);
      }
    };

    const handleLocationFetch = () => {
      if (!clientLocation) {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const { latitude: lat, longitude: lng } = position.coords;
              fetchLocation(lat, lng);
            },
            (error) => {
              toast.error(error.message)
              console.error("Geolocation error:", error);
              dispatch(setLocation({ isLoading: false }));
            }
          );
        }
      } else {
        const location = JSON.parse(clientLocation);
        dispatch(setLocation({ ...location, isLoading: false }));
        router.refresh();
      }
    };

    handleLocationFetch();
  }, [dispatch,Cookies.get("user_token")]);

  return null
};

export default LocationHandler;
