// hooks/useLocationFinder.ts
import { useEffect } from "react";
import { useAppDispatch } from "../redux/hooks"; // Adjust the import path as necessary
import { setUserLocation } from "../slices/common/locationSlice/locationSlice";

const useLocationFinder = (lat: number | null, lng: number | null) => {
  const dispatch = useAppDispatch();

  useEffect(() => {
    if (lat && lng) {
      const getLocationName = async () => {
        if (!window.google) {
          console.error("Google Maps API is not available.");
          return;
        }

        const geocoder = new window.google.maps.Geocoder();
        const latLng = { lat, lng };

        try {
          const results = await new Promise<google.maps.GeocoderResult[]>(
            (resolve, reject) => {
              geocoder.geocode({ location: latLng }, (results, status) => {
                if (status === "OK" && results) {
                  resolve(results);
                } else {
                  reject(status);
                }
              });
            }
          );

          if (results[0]) {
            dispatch(
              setUserLocation({ display_name: results[0].formatted_address })
            );
          } else {
            dispatch(setUserLocation({ display_name: "No address found" }));
          }
        } catch (error) {
          console.error("Geocoder failed due to:", error);
          dispatch(
            setUserLocation({ display_name: "Unable to fetch address." })
          );
        }
      };

      getLocationName();
    }
  }, [lat, lng, dispatch]); // Make sure to include dispatch as a dependency
};

export default useLocationFinder;
