"use client"

import { useEffect, useRef } from "react"

interface ShippingChokepoint {
  name: string
  lat: number
  lng: number
  country: string
  dailyOilMn: number
  percentWorldOil: number
  riskLevel: string
  description: string
}

interface Props {
  data: ShippingChokepoint[]
  onSelect: (point: ShippingChokepoint) => void
}

type LeafletModule = typeof import("leaflet")
type LeafletMap = ReturnType<LeafletModule["map"]>
type LeafletLayerGroup = ReturnType<LeafletModule["layerGroup"]>
type LeafletDefaultIcon = {
  prototype: {
    _getIconUrl?: unknown
  }
  mergeOptions: LeafletModule["Icon"]["Default"]["mergeOptions"]
}

const riskColor: Record<string, string> = {
  Critical: "#ef4444",
  High: "#f59e0b",
  Medium: "#3b7dd8",
  Low: "#4ade80",
}

function getRadius(dailyOilMn: number): number {
  if (dailyOilMn > 15) return 22
  if (dailyOilMn > 10) return 18
  if (dailyOilMn > 5) return 14
  return 10
}

export default function ShippingMap({ data, onSelect }: Props) {
  const mapRef = useRef<HTMLDivElement>(null)
  const mapInstanceRef = useRef<LeafletMap | null>(null)
  const markersLayerRef = useRef<LeafletLayerGroup | null>(null)
  const onSelectRef = useRef(onSelect)

  useEffect(() => {
    onSelectRef.current = onSelect
  }, [onSelect])

  function drawMarkers(
    L: LeafletModule,
    layer: LeafletLayerGroup,
    points: ShippingChokepoint[],
  ) {
    points.forEach((point) => {
      const circle = L.circleMarker([point.lat, point.lng], {
        radius: getRadius(point.dailyOilMn),
        fillColor: riskColor[point.riskLevel] || "#3b7dd8",
        color: "#ffffff",
        weight: 1.5,
        fillOpacity: 0.85,
      }).addTo(layer)

      circle.bindTooltip(point.name, {
        permanent: false,
        direction: "top",
        className: "parallax-map-tooltip",
      })

      circle.on("click", () => onSelectRef.current(point))
    })
  }

  useEffect(() => {
    if (!mapRef.current || mapInstanceRef.current) return

    let isMounted = true

    import("leaflet").then((L) => {
      // @ts-expect-error Next handles CSS side-effect imports at build time.
      import("leaflet/dist/leaflet.css")

      if (!isMounted || !mapRef.current || mapInstanceRef.current) return

      const defaultIcon = L.Icon.Default as unknown as LeafletDefaultIcon
      delete defaultIcon.prototype._getIconUrl

      defaultIcon.mergeOptions({
        iconRetinaUrl:
          "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png",
        iconUrl:
          "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png",
        shadowUrl:
          "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
      })

      const map = L.map(mapRef.current, {
        center: [20, 20],
        zoom: 2,
        minZoom: 2,
        scrollWheelZoom: false,
        worldCopyJump: true,
      })

      mapInstanceRef.current = map

      L.tileLayer(
        "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png",
        {
          attribution: "&copy; OpenStreetMap &copy; CARTO",
          subdomains: "abcd",
          maxZoom: 19,
        },
      ).addTo(map)

      const layerGroup = L.layerGroup().addTo(map)
      markersLayerRef.current = layerGroup
      drawMarkers(L, layerGroup, data)
    })

    return () => {
      isMounted = false

      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove()
        mapInstanceRef.current = null
        markersLayerRef.current = null
      }
    }
    // The Leaflet map is intentionally initialized once; marker updates happen
    // in the separate data effect below.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (!mapInstanceRef.current || !markersLayerRef.current) return

    import("leaflet").then((L) => {
      if (!markersLayerRef.current) return

      markersLayerRef.current.clearLayers()
      drawMarkers(L, markersLayerRef.current, data)
    })
  }, [data])

  return (
    <div
      ref={mapRef}
      style={{
        height: "520px",
        width: "100%",
        borderRadius: "12px",
        border: "1px solid var(--color-border)",
        background: "var(--color-surface)",
      }}
    />
  )
}
