import { useEffect, useRef } from 'react'
import L from 'leaflet'
import { useMap } from 'react-leaflet'
import type { MapRectangle, ActionMode } from './types'
import { newGuid } from './flightPlanUtils'

interface Props {
  color: string
  actionMode: ActionMode
  rectangles: MapRectangle[]
  setRectangles: React.Dispatch<React.SetStateAction<MapRectangle[]>>
}

export default function DrawControl({ color, actionMode, setRectangles }: Props) {
  const map = useMap()
  const startRef = useRef<L.LatLng | null>(null)
  const previewRef = useRef<L.Rectangle | null>(null)
  const colorRef = useRef(color)

  useEffect(() => { colorRef.current = color }, [color])

  useEffect(() => {
    const drawing = actionMode === 'workArea' || actionMode === 'prohibitedArea'
    if (!drawing) return

    const container = map.getContainer()
    const prevCursor = container.style.cursor
    container.style.cursor = 'crosshair'

    const onDown = (e: L.LeafletMouseEvent) => {
      startRef.current = e.latlng
      map.dragging.disable()
      if (previewRef.current) { map.removeLayer(previewRef.current); previewRef.current = null }
    }

    const onMove = (e: L.LeafletMouseEvent) => {
      if (!startRef.current) return
      const bounds = L.latLngBounds(startRef.current, e.latlng)
      if (previewRef.current) {
        previewRef.current.setBounds(bounds)
      } else {
        previewRef.current = L.rectangle(bounds, { color: colorRef.current, weight: 2, fillOpacity: 0.2 }).addTo(map)
      }
    }

    const onUp = (e: L.LeafletMouseEvent) => {
      if (!startRef.current) return
      const start = startRef.current
      const end = e.latlng
      startRef.current = null
      map.dragging.enable()
      if (previewRef.current) { map.removeLayer(previewRef.current); previewRef.current = null }

      if (Math.abs(start.lat - end.lat) < 1e-6 && Math.abs(start.lng - end.lng) < 1e-6) return
      const bounds = L.latLngBounds(start, end)
      const layer = L.rectangle(bounds, { color: colorRef.current, weight: 2, fillOpacity: 0.2 }).addTo(map)
      setRectangles(prev => [...prev, { id: newGuid(), layer, color: colorRef.current as 'red' | 'green', bounds }])
    }

    map.on('mousedown', onDown)
    map.on('mousemove', onMove)
    map.on('mouseup', onUp)

    return () => {
      map.off('mousedown', onDown)
      map.off('mousemove', onMove)
      map.off('mouseup', onUp)
      container.style.cursor = prevCursor
      map.dragging.enable()
      if (previewRef.current) { map.removeLayer(previewRef.current); previewRef.current = null }
      startRef.current = null
    }
  }, [actionMode, map, setRectangles])

  return null
}
