'use client'

import { useState, useCallback, useEffect, useRef } from 'react'
import { MapPin, Bed, Maximize, ExternalLink } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { formatPrice } from '@/lib/utils'

let leafletCssLoaded = false
function ensureLeafletCss() {
  if (leafletCssLoaded || typeof document === 'undefined') return
  const existing = document.querySelector('link[href*="leaflet"]')
  if (existing) { leafletCssLoaded = true; return }
  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'
  document.head.appendChild(link)
  leafletCssLoaded = true
}

interface Property {
  id: string; title: string; price: number; type: string; status: string
  city: string; neighborhood: string; latitude: number; longitude: number
  images: string[]; bedrooms?: number | null; bathrooms?: number | null; area: number
  has3D?: boolean; hasVirtualTour?: boolean; boundaries?: any
}

interface PropertyMapProps {
  properties: Property[]
  onSelect?: (property: Property | null) => void
  selectedId?: string
  height?: string
  initialCity?: string
}

const TYPE_CONFIG: Record<string, { color: string }> = {
  APARTMENT:  { color: '#1d4ed8' },
  VILLA:      { color: '#16a34a' },
  COMMERCIAL: { color: '#d97706' },
  LAND:       { color: '#7c3aed' },
  RIAD:       { color: '#dc2626' },
}

const TYPE_LABELS: Record<string, string> = {
  APARTMENT: 'شقة', VILLA: 'فيلا', COMMERCIAL: 'تجاري', LAND: 'أرض', RIAD: 'رياض',
}

const CITY_COORDS: Record<string, [number, number]> = {
  'الدار البيضاء': [-7.5898, 33.5731],
  'الرباط':        [-6.8498, 34.0209],
  'مراكش':         [-7.9811, 31.6295],
  'فاس':           [-4.9998, 34.0331],
  'طنجة':          [-5.7998, 35.7595],
  'أكادير':        [-9.5981, 30.4278],
}

export function PropertyMap({
  properties,
  onSelect,
  selectedId,
  height = '500px',
  initialCity,
}: PropertyMapProps) {
  const [popup, setPopup] = useState<Property | null>(null)
  const [mapStyle, setMapStyle] = useState<'streets' | 'satellite'>('streets')
  const mapContainerRef = useRef<HTMLDivElement>(null)
  const mapInstanceRef = useRef<any>(null)
  const leafletRef = useRef<any>(null)
  const markersLayerRef = useRef<any>(null)
  const streetsRef = useRef<any>(null)
  const satelliteRef = useRef<any>(null)

  const initialCoords = initialCity && CITY_COORDS[initialCity]
    ? CITY_COORDS[initialCity]
    : [-7.09, 31.79]

  const zoom = initialCity && CITY_COORDS[initialCity] ? 12 : 5.5

  useEffect(() => {
    if (!mapContainerRef.current || mapInstanceRef.current) return
    if (typeof window === 'undefined') return

    let cancelled = false

    const init = async () => {
      ensureLeafletCss()
      const L = (await import('leaflet')).default
      if (cancelled) return

      const map = L.map(mapContainerRef.current!, {
        center: [initialCoords[1], initialCoords[0]],
        zoom,
        zoomControl: false,
        scrollWheelZoom: true,
      })

      L.control.zoom({ position: 'topleft' }).addTo(map)
      L.control.scale({ position: 'bottomleft' }).addTo(map)

      const streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap',
        maxZoom: 19,
      })

      const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: '© Esri',
        maxZoom: 18,
      })

      streets.addTo(map)
      streetsRef.current = streets
      satelliteRef.current = satellite

      const markersLayer = L.layerGroup().addTo(map)
      markersLayerRef.current = markersLayer

      mapInstanceRef.current = map
      leafletRef.current = L

      setTimeout(() => map.invalidateSize(), 100)
    }

    init()

    return () => {
      cancelled = true
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove()
        mapInstanceRef.current = null
      }
    }
  }, [])

  useEffect(() => {
    const map = mapInstanceRef.current
    const L = leafletRef.current
    const markersLayer = markersLayerRef.current
    if (!map || !L || !markersLayer) return

    markersLayer.clearLayers()

    properties.forEach(p => {
      const cfg = TYPE_CONFIG[p.type] ?? { color: '#6b7280' }
      const isSelected = p.id === selectedId

      const priceLabel = p.price >= 1_000_000
        ? `${(p.price / 1_000_000).toFixed(1)}M`
        : p.price >= 1_000
          ? `${(p.price / 1_000).toFixed(0)}K`
          : `${p.price}`

      const icon = L.divIcon({
        className: '',
        html: `<div style="position:relative;cursor:pointer;${isSelected ? 'transform:scale(1.25);z-index:999' : ''}"><div style="background:${cfg.color};color:#fff;font-weight:700;font-size:11px;padding:4px 8px;border-radius:20px;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.25);border:2px solid ${isSelected ? '#facc15' : '#fff'}">${priceLabel}</div><div style="width:0;height:0;margin:0 auto;border-left:5px solid transparent;border-right:5px solid transparent;border-top:7px solid ${cfg.color}"></div></div>`,
        iconSize: [0, 0],
        iconAnchor: [20, 25],
      })

      const marker = L.marker([p.latitude, p.longitude], { icon }).addTo(markersLayer)
      marker.on('click', () => {
        setPopup(p)
        onSelect?.(p)
        map.flyTo([p.latitude, p.longitude], 13, { duration: 0.8 })
      })
    })
  }, [properties, selectedId, onSelect])

  useEffect(() => {
    const map = mapInstanceRef.current
    if (!map) return
    if (mapStyle === 'satellite') {
      if (streetsRef.current?.hasLayer) map.removeLayer(streetsRef.current)
      satelliteRef.current?.addTo(map)
    } else {
      if (satelliteRef.current) map.removeLayer(satelliteRef.current)
      streetsRef.current?.addTo(map)
    }
  }, [mapStyle])

  const flyToCity = (city: string) => {
    const map = mapInstanceRef.current
    if (!map || !CITY_COORDS[city]) return
    const [lng, lat] = CITY_COORDS[city]
    map.flyTo([lat, lng], 12, { duration: 1 })
  }

  return (
    <div className="relative rounded-xl overflow-hidden" style={{ height }}>
      <div ref={mapContainerRef} style={{ width: '100%', height: '100%' }} />

      <div className="absolute top-3 right-14 flex gap-1.5 z-[1000]">
        {Object.entries(CITY_COORDS).slice(0, 4).map(([city]) => (
          <button
            key={city}
            onClick={() => flyToCity(city)}
            className="bg-white/90 backdrop-blur text-xs text-gray-700 px-2.5 py-1.5 rounded-lg shadow hover:bg-white transition-colors border border-gray-100"
          >
            {city.split('').slice(0, 3).join('')}
          </button>
        ))}
      </div>

      <div className="absolute bottom-8 left-3 z-[1000]">
        <button
          onClick={() => setMapStyle(s => s === 'streets' ? 'satellite' : 'streets')}
          className="bg-white/90 backdrop-blur text-xs text-gray-700 px-3 py-2 rounded-xl shadow hover:bg-white border border-gray-100 font-medium"
        >
          {mapStyle === 'streets' ? '🛰️ قمر' : '🗺️ خريطة'}
        </button>
      </div>

      <div className="absolute bottom-8 right-3 bg-white/90 backdrop-blur rounded-xl shadow p-2.5 flex flex-col gap-1.5 border border-gray-100 z-[1000]">
        {Object.entries(TYPE_CONFIG).map(([type, cfg]) => (
          <div key={type} className="flex items-center gap-2 text-xs text-gray-600">
            <div className="w-3 h-3 rounded-full shrink-0" style={{ background: cfg.color }} />
            {TYPE_LABELS[type]}
          </div>
        ))}
      </div>

      {popup && (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-[1000] w-72 bg-white rounded-xl shadow-2xl overflow-hidden border" dir="rtl">
          <div className="relative h-28">
            <Image
              src={popup.images?.[0] || '/placeholder-property.jpg'}
              alt={popup.title}
              fill
              className="object-cover"
              sizes="288px"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />
            <div className="absolute bottom-2 right-2 flex gap-1">
              {popup.has3D && <span className="bg-purple-600 text-white text-xs px-2 py-0.5 rounded-full">3D</span>}
              {popup.hasVirtualTour && <span className="bg-green-600 text-white text-xs px-2 py-0.5 rounded-full">360°</span>}
            </div>
            <button
              onClick={() => { setPopup(null); onSelect?.(null) }}
              className="absolute top-2 left-2 bg-white/80 rounded-full w-6 h-6 flex items-center justify-center text-gray-600 hover:bg-white text-xs"
            >
              ✕
            </button>
          </div>
          <div className="p-3">
            <h3 className="font-bold text-sm line-clamp-1 mb-1">{popup.title}</h3>
            <div className="flex items-center gap-1 text-xs text-gray-500 mb-2">
              <MapPin className="w-3 h-3" />
              {popup.neighborhood}، {popup.city}
            </div>
            <p className="text-blue-600 font-bold text-base mb-3">{formatPrice(popup.price)}</p>
            <div className="flex gap-3 text-xs text-gray-500 mb-3">
              {popup.bedrooms && (
                <span className="flex items-center gap-1">
                  <Bed className="w-3.5 h-3.5" /> {popup.bedrooms} غرف
                </span>
              )}
              <span className="flex items-center gap-1">
                <Maximize className="w-3.5 h-3.5" /> {popup.area} م²
              </span>
            </div>
            <Link
              href={`/properties/${popup.id}`}
              className="flex items-center justify-center gap-1.5 w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-sm font-medium transition-colors"
            >
              عرض التفاصيل <ExternalLink className="w-3.5 h-3.5" />
            </Link>
          </div>
        </div>
      )}
    </div>
  )
}
