'use client'

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

type PropertyLocationMapProps = {
  title: string
  location: string
  address: string
  coordinates: [number, number]
  lang: Language
}

export default function PropertyLocationMap({
  title,
  location,
  address,
  coordinates,
  lang,
}: PropertyLocationMapProps) {
  const mapNodeRef = useRef<HTMLDivElement | null>(null)
  const mapRef = useRef<LeafletMap | null>(null)
  const markerRef = useRef<Marker | null>(null)
  const directionsUrl = `https://www.openstreetmap.org/directions?to=${coordinates[0]}%2C${coordinates[1]}`

  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: coordinates,
        zoom: 16,
        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 markerIcon = L.divIcon({
        className: 'kv-map-marker',
        html: '<span></span>',
        iconSize: [34, 34],
        iconAnchor: [17, 17],
        popupAnchor: [0, -18],
      })

      const marker = L.marker(coordinates, { icon: markerIcon })
        .addTo(map)
        .bindPopup(`
          <div class="kv-map-popup">
            <strong>${title}</strong>
            <span>${location}</span>
            <p>${address}</p>
            <div><a href="${directionsUrl}" target="_blank" rel="noopener noreferrer">${getTranslation(lang, 'propertyDetail.openMap')}</a></div>
          </div>
        `)

      marker.openPopup()
      markerRef.current = marker
      mapRef.current = map
    }

    loadMap()

    return () => {
      cancelled = true
      if (mapRef.current) {
        mapRef.current.remove()
        mapRef.current = null
        markerRef.current = null
      }
    }
  }, [address, coordinates, directionsUrl, lang, location, title])

  return (
    <section id="map" className="py-16 px-6 bg-white scroll-mt-24">
      <div className="max-w-6xl mx-auto">
        <div className="grid lg:grid-cols-[0.9fr_1.3fr] 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, 'propertyDetail.location')}
            </span>
            <h3 className="font-semibold text-2xl md:text-3xl text-brand-text mb-5">
              {title}
            </h3>
            <div className="flex items-start gap-3 rounded-2xl border-2 border-brand-accent/40 bg-brand-off-white p-5">
              <MapPin className="mt-1 text-brand-primary shrink-0" size={22} />
              <div>
                <p className="text-sm font-bold uppercase tracking-wide text-brand-text">{location}</p>
                <p className="text-sm leading-relaxed text-brand-text/65 mt-2">{address}</p>
              </div>
            </div>
            <a
              href={directionsUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-5 inline-flex w-fit items-center gap-2 rounded-full border-2 border-brand-primary px-5 py-3 text-xs font-bold uppercase tracking-wide text-brand-primary hover:bg-brand-primary hover:text-white transition-colors"
            >
              {getTranslation(lang, 'propertyDetail.openMap')}
              <ExternalLink size={14} />
            </a>
          </div>

          <div className="relative min-h-[360px] sm:min-h-[460px] overflow-hidden rounded-2xl border-2 border-brand-primary bg-brand-sand shadow-xl">
            <div ref={mapNodeRef} className="absolute inset-0" aria-label={`${title} ${getTranslation(lang, 'propertyDetail.location')}`} />
            <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>
    </section>
  )
}
