import { useEffect } from 'react';
import { useMap, useMapEvents } from 'react-leaflet';
import type { LeafletMouseEvent } from 'leaflet';

interface Props {
  active: boolean;
  onMapClick: (lat: number, lng: number) => void;
}

function AddLocationHandler({ onMapClick }: { onMapClick: (lat: number, lng: number) => void }) {
  useMapEvents({
    click(e: LeafletMouseEvent) {
      onMapClick(e.latlng.lat, e.latlng.lng);
    },
  });
  return null;
}

export default function AddLocationMode({ active, onMapClick }: Props) {
  const map = useMap();

  useEffect(() => {
    if (active) {
      map.getContainer().style.cursor = 'crosshair';
      map.doubleClickZoom.disable();
    } else {
      map.getContainer().style.cursor = '';
      map.doubleClickZoom.enable();
    }
    return () => {
      map.getContainer().style.cursor = '';
      map.doubleClickZoom.enable();
    };
  }, [active, map]);

  if (!active) return null;
  return <AddLocationHandler onMapClick={onMapClick} />;
}
