import { useEffect, useRef } from 'react'

import { cn } from './utils'
import { ThreatMap } from '../../visualization/map'
import type { MapMarker, MapRegion, MapConfig } from '../../visualization/map/types'

export type { MapMarker, MapRegion } from '../../visualization/map/types'

export interface MapProps {
  center?: { lat: number; lng: number }
  zoom?: number
  markers?: MapMarker[]
  regions?: MapRegion[]
  tileUrl?: string
  minZoom?: number
  maxZoom?: number
  onMarkerClick?: (marker: MapMarker) => void
  onRegionClick?: (region: MapRegion) => void
  className?: string
}

function Map({
  center,
  zoom,
  markers,
  regions,
  tileUrl,
  minZoom,
  maxZoom,
  onMarkerClick,
  onRegionClick,
  className,
}: MapProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const instanceRef = useRef<ThreatMap | null>(null)

  const onMarkerClickRef = useRef(onMarkerClick)
  onMarkerClickRef.current = onMarkerClick
  const onRegionClickRef = useRef(onRegionClick)
  onRegionClickRef.current = onRegionClick

  useEffect(() => {
    const container = containerRef.current
    if (!container) return

    const cfg: MapConfig = {
      container,
      onMarkerClick: marker => onMarkerClickRef.current?.(marker),
      onRegionClick: region => onRegionClickRef.current?.(region),
    }
    if (center !== undefined) cfg.center = center
    if (zoom !== undefined) cfg.zoom = zoom
    if (markers !== undefined) cfg.markers = markers
    if (regions !== undefined) cfg.regions = regions
    if (tileUrl !== undefined) cfg.tileUrl = tileUrl
    if (minZoom !== undefined) cfg.minZoom = minZoom
    if (maxZoom !== undefined) cfg.maxZoom = maxZoom

    instanceRef.current = new ThreatMap(cfg)

    return () => {
      instanceRef.current?.destroy()
      instanceRef.current = null
    }
    // Re-create when structural config changes
  }, [tileUrl, minZoom, maxZoom])

  // Update center and zoom
  useEffect(() => {
    if (instanceRef.current && center) {
      instanceRef.current.setCenter(center.lat, center.lng)
    }
  }, [center])

  useEffect(() => {
    if (instanceRef.current && zoom !== undefined) {
      instanceRef.current.setZoom(zoom)
    }
  }, [zoom])

  return (
    <div
      ref={containerRef}
      data-slot="map"
      className={cn('relative h-full w-full overflow-hidden', className)}
    />
  )
}
Map.displayName = 'Map'

export { Map }
