"use client"

import { useEffect, useRef } from "react"
import { useRouter } from "next/navigation"
import "leaflet/dist/leaflet.css"
import "leaflet.markercluster/dist/MarkerCluster.css"
import "leaflet.markercluster/dist/MarkerCluster.Default.css"
import { communityToSlug, stateToSlug, type WaltonwoodCity, type WaltonwoodStateLocation } from "@/lib/waltonwood-locations"

type Props = {
  locations: WaltonwoodStateLocation[]
  activeState: string
  activeCommunity: string | null
  onSelectPin: (state: string, community: string) => void
}

const RED_PIN_ICON_HTML = `
  <svg width="34" height="46" viewBox="0 0 34 46" xmlns="http://www.w3.org/2000/svg" style="display:block;filter:drop-shadow(0 3px 3px rgba(0,0,0,0.35))">
    <defs>
      <linearGradient id="wwPinGradient" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stop-color="#F04B4B"/>
        <stop offset="100%" stop-color="#B91C1C"/>
      </linearGradient>
    </defs>
    <ellipse cx="17" cy="42" rx="6" ry="2" fill="#000000" opacity="0.18"/>
    <path d="M17 2C9.82 2 4 7.82 4 15c0 9.5 13 25 13 25s13-15.5 13-25C30 7.82 24.18 2 17 2z" fill="url(#wwPinGradient)" stroke="#7F1D1D" stroke-width="1"/>
    <circle cx="17" cy="15" r="9" fill="#FFFFFF" opacity="0.95"/>
    <circle cx="17" cy="15" r="5.5" fill="#B91C1C"/>
  </svg>
`

export default function WaltonwoodLeafletMap({ locations, activeState, activeCommunity, onSelectPin }: Props) {
  const router = useRouter()
  const containerRef = useRef<HTMLDivElement | null>(null)
  const mapRef = useRef<any>(null)
  const markersRef = useRef<Record<string, any>>({})
  const onSelectPinRef = useRef(onSelectPin)
  onSelectPinRef.current = onSelectPin
  const wheelCleanupRef = useRef<(() => void) | null>(null)

  useEffect(() => {
    let cancelled = false

    async function init() {
      const L = (await import("leaflet")).default
      await import("leaflet.markercluster")

      if (cancelled || !containerRef.current || mapRef.current) return

      const redIcon = L.divIcon({
        html: RED_PIN_ICON_HTML,
        className: "waltonwood-red-pin",
        iconSize: [34, 46],
        iconAnchor: [17, 44],
        popupAnchor: [0, -40],
      })

      const map = L.map(containerRef.current, {
        scrollWheelZoom: true,
      }).setView([38.5, -87], 5)
      mapRef.current = map

      const hintEl = document.createElement("div")
      hintEl.className = "waltonwood-scroll-hint"
      hintEl.textContent = "Use Ctrl + scroll to zoom the map"
      containerRef.current.appendChild(hintEl)
      let hintTimeout: ReturnType<typeof setTimeout> | undefined

      const wheelHandler = (e: WheelEvent) => {
        if (e.ctrlKey || e.metaKey) {
          e.preventDefault()
          hintEl.classList.remove("is-visible")
          return
        }
        e.stopPropagation()
        hintEl.classList.add("is-visible")
        if (hintTimeout) clearTimeout(hintTimeout)
        hintTimeout = setTimeout(() => hintEl.classList.remove("is-visible"), 1200)
      }
      containerRef.current.addEventListener("wheel", wheelHandler, {
        passive: false,
        capture: true,
      })
      wheelCleanupRef.current = () => {
        containerRef.current?.removeEventListener("wheel", wheelHandler, { capture: true } as any)
        hintEl.remove()
        if (hintTimeout) clearTimeout(hintTimeout)
      }

      const maptilerKey = process.env.NEXT_PUBLIC_MAPTILER_KEY

      L.tileLayer(
        `https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=${maptilerKey}`,
        {
          attribution:
            '&copy; <a href="https://www.maptiler.com/copyright/" target="_blank">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors',
          maxZoom: 19,
          tileSize: 512,
          zoomOffset: -1,
        }
      ).addTo(map)

      const clusterGroup = (L as any).markerClusterGroup({
        spiderfyOnMaxZoom: true,
        showCoverageOnHover: false,
        maxClusterRadius: 2,
        disableClusteringAtZoom: 9,
        iconCreateFunction: (cluster: any) => {
          const count = cluster.getChildCount()
          return L.divIcon({
            html: `<div style="display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:50%;background:linear-gradient(180deg,#F04B4B,#B91C1C);border:3px solid #FFFFFF;color:#FFFFFF;font-weight:700;font-size:14px;box-shadow:0 3px 6px rgba(0,0,0,0.35)">${count}</div>`,
            className: "waltonwood-cluster-icon",
            iconSize: [40, 40],
          })
        },
      })

      const allLatLngs: [number, number][] = []
      let activePopupMarker: any = null
      let closeTimeout: ReturnType<typeof setTimeout> | undefined

      const closeActivePopup = () => {
        if (activePopupMarker) {
          activePopupMarker.closePopup()
          activePopupMarker = null
        }
      }

      locations.forEach((loc) => {
        loc.cities.forEach((city: WaltonwoodCity) => {
          const marker = L.marker([city.lat, city.lng], { icon: redIcon })
          marker.bindPopup(
            `<div style="font-family:inherit;min-width:190px">
              <p style="margin:0 0 4px;font-weight:600;color:#1D1D1D">${city.community}</p>
              <p style="margin:0 0 8px;font-size:12px;color:#5F5F5F">${city.address}</p>
              <a href="/waltonwood-senior-living/${stateToSlug(loc.state)}/${communityToSlug(city.community)}" style="display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:600;color:#8B783D;text-transform:uppercase;letter-spacing:0.05em;text-decoration:none;cursor:pointer">View Details &rarr;</a>
            </div>`,
            { closeButton: false, offset: [0, -6], autoPan: true, autoPanPadding: [20, 20] }
          )

          marker.on("mouseover", () => {
            if (closeTimeout) clearTimeout(closeTimeout)
            if (activePopupMarker && activePopupMarker !== marker) {
              activePopupMarker.closePopup()
            }
            activePopupMarker = marker
            marker.openPopup()
          })
          marker.on("mouseout", () => {
            closeTimeout = setTimeout(() => {
              closeActivePopup()
            }, 200)
          })
          marker.getPopup()?.on("add", () => {
            const popupEl = marker.getPopup()?.getElement()
            popupEl?.addEventListener("mouseenter", () => {
              if (closeTimeout) clearTimeout(closeTimeout)
            })
            popupEl?.addEventListener("mouseleave", () => {
              closeTimeout = setTimeout(() => {
                closeActivePopup()
              }, 200)
            })
          })
          marker.on("click", () => {
            onSelectPinRef.current(loc.state, city.community)
          })
          markersRef.current[city.community] = marker
          clusterGroup.addLayer(marker)
          allLatLngs.push([city.lat, city.lng])
        })
      })

      map.addLayer(clusterGroup)

      const initialStateLoc = locations.find((loc) => loc.state === activeState)
      const initialBounds =
        initialStateLoc && initialStateLoc.cities.length > 0
          ? initialStateLoc.cities.map((city) => [city.lat, city.lng] as [number, number])
          : allLatLngs

      if (initialBounds.length > 0) {
        map.fitBounds(initialBounds as any, { padding: [50, 50], maxZoom: 12 })
      }
    }

    init()

    return () => {
      cancelled = true
      if (wheelCleanupRef.current) {
        wheelCleanupRef.current()
        wheelCleanupRef.current = null
      }
      if (mapRef.current) {
        mapRef.current.remove()
        mapRef.current = null
        markersRef.current = {}
      }
    }
  }, [locations])

  useEffect(() => {
    if (activeCommunity) return
    const map = mapRef.current
    if (!map) return
    const stateLoc = locations.find((loc) => loc.state === activeState)
    if (!stateLoc || stateLoc.cities.length === 0) return
    const bounds = stateLoc.cities.map((city) => [city.lat, city.lng]) as [number, number][]
    map.flyToBounds(bounds, { padding: [50, 50], maxZoom: 12 })
  }, [activeState, locations, activeCommunity])

  useEffect(() => {
    if (!activeCommunity) return
    const marker = markersRef.current[activeCommunity]
    const map = mapRef.current
    if (!marker || !map) return
    map.setView(marker.getLatLng(), Math.max(map.getZoom(), 12), { animate: true })
    marker.openPopup()
  }, [activeCommunity])

  return (
    <>
      <style>{`
        .waltonwood-scroll-hint {
          position: absolute;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(0, 0, 0, 0.35);
          color: #FFFFFF;
          font-size: 14px;
          font-weight: 600;
          letter-spacing: 0.02em;
          z-index: 1000;
          opacity: 0;
          pointer-events: none;
          transition: opacity 0.15s ease;
        }
        .waltonwood-scroll-hint.is-visible {
          opacity: 1;
        }
      `}</style>
      <div
        ref={containerRef}
        className="isolate relative z-0 h-[460px] w-full overflow-hidden rounded-2xl shadow-md sm:h-[520px] lg:h-[600px]"
      />
    </>
  )
}
