import { useState, useEffect } from 'react';
import { useMap, useMapEvents, CircleMarker, Popup } from 'react-leaflet';
import { Button, Space } from 'antd';
import type { LeafletMouseEvent } from 'leaflet';

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

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

export default function MoveLocationMode({ active, onConfirmMove, onCancel }: Props) {
  const map = useMap();
  const [target, setTarget] = useState<[number, number] | null>(null);

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

  if (!active) return null;

  return (
    <>
      {!target && <MoveHandler onClickMap={(lat, lng) => setTarget([lat, lng])} />}
      {target && (
        <CircleMarker
          center={target}
          radius={10}
          pathOptions={{ fillColor: '#9d4edd', fillOpacity: 0.9, color: '#fff', weight: 2 }}
        >
          <Popup autoClose={false} closeOnClick={false}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ marginBottom: 8, fontWeight: 600 }}>Confirm move?</div>
              <div style={{ fontSize: 11, marginBottom: 8, color: 'rgba(255,255,255,0.65)' }}>
                {target[0].toFixed(5)}, {target[1].toFixed(5)}
              </div>
              <Space>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => onConfirmMove(target[0], target[1])}
                >
                  Confirm
                </Button>
                <Button size="small" onClick={onCancel}>
                  Cancel
                </Button>
              </Space>
            </div>
          </Popup>
        </CircleMarker>
      )}
    </>
  );
}
