'use client'

import { useEffect, useMemo, useRef, useState } from 'react'
import Link from 'next/link'
import { MapPin } from 'lucide-react'
import type { Map as LeafletMap, Marker } from 'leaflet'
import type { Language } from '@/lib/i18n'
import { getTranslation } from '@/lib/i18n'

type PropertyMapPin = {
  id: string
  title: string
  slugs: string[]
  address: string
  area: string
  coordinates: [number, number]
}

const propertyMapPins: PropertyMapPin[] = [
  {
    id: 'sailview-ph314',
    title: 'Sail View PH 314',
    slugs: ['sailview-ph314'],
    address: 'Calle Francisca Rodriguez 232, Emiliano Zapata, 48380 Puerto Vallarta, Jal.',
    area: 'Zona Romantica',
    coordinates: [20.600990443494673, -105.23538787270093],
  },
  {
    id: 'soho-pv',
    title: 'SOHO PV PH4 & 1002',
    slugs: ['soho-ph4', 'soho-1002'],
    address: 'Insurgentes 466, Alta Vista, 48380 Puerto Vallarta, Jal.',
    area: 'Alta Vista',
    coordinates: [20.601018825279116, -105.23346951729509],
  },
  {
    id: 'horizon-505',
    title: 'Horizon 505',
    slugs: ['horizon-505'],
    address: 'Cda. de Los Pinos 143, Amapas - Conchas Chinas, 48399 Puerto Vallarta, Jal.',
    area: 'Amapas',
    coordinates: [20.59431028094856, -105.2382114747934],
  },
  {
    id: 'avida510',
    title: 'AVIDA 510',
    slugs: ['avida510'],
    address: 'Insurgentes 193, Zona Romantica, Emiliano Zapata, 48380 Puerto Vallarta, Jal.',
    area: 'Emiliano Zapata',
    coordinates: [20.604662408509327, -105.23363460362917],
  },
]

type OurPropertiesMapProps = {
  lang: Language
}

export default function OurPropertiesMap({ lang }: OurPropertiesMapProps) {
  const mapNodeRef = useRef<HTMLDivElement | null>(null)
  const mapRef = useRef<LeafletMap | null>(null)
  const markersRef = useRef<Record<string, Marker>>({})
  const [activePinId, setActivePinId] = useState(propertyMapPins[0].id)

  const center = useMemo<[number, number]>(() => [20.5986, -105.2372], [])

  useEffect(() => {
    let cancelled = false

    async function loadMap() {
      if (!mapNodeRef.current || mapRef.current) return
      const L = await import('leaflet')
      if (cancelled || !mapNodeRef.current) return

      const map = L.map(mapNodeRef.current, {
        center,
        zoom: 15,
        scrollWheelZoom: false,
        zoomControl: false,
      })

      L.control.zoom({ position: 'bottomright' }).addTo(map)
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors',
        maxZoom: 19,
      }).addTo(map)

      const bounds = L.latLngBounds(propertyMapPins.map((pin) => pin.coordinates))
      const markerIcon = L.divIcon({
        className: 'kv-map-marker',
        html: '<span></span>',
        iconSize: [34, 34],
        iconAnchor: [17, 17],
        popupAnchor: [0, -18],
      })

      for (const pin of propertyMapPins) {
        const links = pin.slugs
          .map((slug) => `<a href="/${lang}/properties/${slug}/">${getTranslation(lang, 'properties.viewProperty')}</a>`)
          .join('')

        const marker = L.marker(pin.coordinates, { icon: markerIcon })
          .addTo(map)
          .bindPopup(`
            <div class="kv-map-popup">
              <strong>${pin.title}</strong>
              <span>${pin.area}</span>
              <p>${pin.address}</p>
              <div>${links}</div>
            </div>
          `)

        marker.on('click', () => setActivePinId(pin.id))
        markersRef.current[pin.id] = marker
      }

      map.fitBounds(bounds, { padding: [40, 40], maxZoom: 15 })
      mapRef.current = map
    }

    loadMap()

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

  const openPin = (pin: PropertyMapPin) => {
    setActivePinId(pin.id)
    mapRef.current?.setView(pin.coordinates, 16, { animate: true })
    markersRef.current[pin.id]?.openPopup()
  }

  return (
    <section className="py-16 sm:py-20 px-4 sm:px-6 bg-brand-off-white">
      <div className="container mx-auto max-w-6xl">
        <div className="grid lg:grid-cols-[0.8fr_1.2fr] gap-8 lg:gap-10 items-stretch">
          <div className="flex flex-col justify-center">
            <span className="text-[10px] uppercase tracking-[0.45em] text-brand-primary font-bold mb-4">
              {getTranslation(lang, 'ourPropertiesPage.mapEyebrow')}
            </span>
            <h2 className="text-2xl sm:text-3xl md:text-4xl font-extrabold tracking-tighter uppercase leading-tight mb-5 text-brand-text">
              {getTranslation(lang, 'ourPropertiesPage.mapTitle')}
            </h2>
            <p className="text-sm sm:text-base leading-relaxed text-brand-text/70 mb-8 max-w-xl">
              {getTranslation(lang, 'ourPropertiesPage.mapDescription')}
            </p>
            <div className="space-y-3">
              {propertyMapPins.map((pin) => (
                <button
                  key={pin.id}
                  type="button"
                  onClick={() => openPin(pin)}
                  className={`w-full text-left border-2 rounded-xl px-4 py-4 transition-all ${
                    activePinId === pin.id
                      ? 'border-brand-primary bg-white shadow-md'
                      : 'border-brand-accent/35 bg-white/70 hover:border-brand-primary'
                  }`}
                >
                  <span className="flex items-start gap-3">
                    <MapPin className="mt-0.5 text-brand-primary shrink-0" size={18} />
                    <span>
                      <span className="block text-sm font-bold uppercase tracking-wide text-brand-text">{pin.title}</span>
                      <span className="block text-xs leading-relaxed text-brand-text/60 mt-1">{pin.address}</span>
                    </span>
                  </span>
                </button>
              ))}
            </div>
          </div>

          <div className="relative min-h-[420px] sm:min-h-[520px] overflow-hidden rounded-2xl border-2 border-brand-primary bg-brand-sand shadow-xl">
            <div ref={mapNodeRef} className="absolute inset-0" aria-label={getTranslation(lang, 'ourPropertiesPage.mapTitle')} />
            <div className="pointer-events-none absolute inset-0 ring-1 ring-inset ring-black/10" />
            <div className="absolute left-4 top-4 rounded-full bg-white/95 px-4 py-2 text-[10px] font-bold uppercase tracking-[0.25em] text-brand-primary shadow-sm">
              OpenStreetMap
            </div>
          </div>
        </div>

        <div className="mt-8 flex flex-wrap gap-3">
          {propertyMapPins.map((pin) => (
            <Link
              key={`${pin.id}-directions`}
              href={`https://www.openstreetmap.org/directions?to=${pin.coordinates[0]}%2C${pin.coordinates[1]}`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 rounded-full border border-brand-accent/60 bg-white px-4 py-2 text-xs font-semibold uppercase tracking-wide text-brand-text/70 hover:border-brand-primary hover:text-brand-primary transition-colors"
            >
              <MapPin size={14} />
              {pin.title}
            </Link>
          ))}
        </div>
      </div>
    </section>
  )
}
