import { Dispatch, SetStateAction, useEffect } from "react";
import { UseFormClearErrors, UseFormSetValue } from "react-hook-form";
import { Place } from "../../../data/datasource/api/entities/place";
import { Map, Marker, useMap } from "@vis.gl/react-google-maps";
import { LoadingSpinner } from "../loading_spinner/loading_spinner";

// Define the props interface for the component
interface props {
  setValue: UseFormSetValue<Place>;
  isLoading: boolean;
  clearErrors: UseFormClearErrors<Place>;
  position: Position | null;
  setPosition: Dispatch<SetStateAction<Position | null>>;
}

// Define the Position interface
export interface Position {
  latitude: number;
  longitude: number;
}

// Main Google Maps component
export const MapGoogleComponent = ({
  setValue,
  isLoading,
  position,
  setPosition,
  clearErrors,
}: props) => {
  const defaultCenter = { lat: 23.687, lng: -102.74 };
  const mapRef = useMap();

  useEffect(() => {
    if (position && position.latitude !== 0 && position.longitude !== 0) {
      // Update form values with the new position
      setValue("latitude", position.latitude);
      setValue("longitude", position.longitude);
      if (mapRef) {
        // Center the map to the new position
        mapRef.setCenter({ lat: position.latitude, lng: position.longitude });
        mapRef.setZoom(16);
      }
      // Clear any errors related to latitude and longitude
      clearErrors("latitude");
      clearErrors("longitude");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [position]);

  return (
    <div style={{ width: "100%", height: "100%" }}>
      {isLoading && <LoadingSpinner />}
      <Map
        defaultCenter={defaultCenter}
        defaultZoom={8}
        gestureHandling={"greedy"}
        disableDefaultUI={true}
        onClick={(event) => {
          const lat = event.detail.latLng?.lat || 0.0;
          const lng = event.detail.latLng?.lng || 0.0;
          // Update position state when the map is clicked
          setPosition({ latitude: lat, longitude: lng });
        }}
      >
        {position && (
          <Marker
            position={{ lat: position.latitude, lng: position.longitude }}
          />
        )}
      </Map>
    </div>
  );
};
