'use client'

import { useEffect, useRef } from 'react'
import { MapPin } from 'lucide-react'

interface Craftsman {
  id: string; name: string; profession: string; city: string
  latitude: number; longitude: number; image?: string | null
  rating: number; services: any[]
}

export function CraftsmanMap({
  craftsmen, onSelect, selectedId, height = '400px',
}: {
  craftsmen: Craftsman[]
  onSelect?: (c: Craftsman) => void
  selectedId?: string
  height?: string
}) {
  const mapRef = useRef<HTMLDivElement>(null)
  const mapInstance = useRef<any>(null)
  const markers = useRef<any[]>([])

  useEffect(() => {
    if (!mapRef.current || typeof window === 'undefined') 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)

    let L: any
    import('leaflet').then(mod => {
      L = mod.default
      if (!mapRef.current) return

      const map = L.map(mapRef.current, { zoomControl: false }).setView([31.5, -7.0], 6)
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap',
      }).addTo(map)
      mapInstance.current = map

      craftsmen.forEach(c => {
        if (!c.latitude || !c.longitude) return
        const icon = L.divIcon({
          html: `<div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center shadow-lg border-2 border-white" style="font-size:14px">${c.name.charAt(0)}</div>`,
          className: '',
          iconSize: [32, 32],
          iconAnchor: [16, 32],
        })
        const marker = L.marker([c.latitude, c.longitude], { icon })
          .addTo(map)
          .on('click', () => onSelect?.(c))
        markers.current.push(marker)
      })

      if (craftsmen.length > 0) {
        const group = L.featureGroup(markers.current)
        map.fitBounds(group.getBounds().pad(0.1))
      }
    })

    return () => {
      markers.current = []
      if (mapInstance.current) { mapInstance.current.remove(); mapInstance.current = null }
    }
  }, [craftsmen.length])

  useEffect(() => {
    if (!selectedId || !mapInstance.current) return
    const c = craftsmen.find(c => c.id === selectedId)
    if (c) mapInstance.current.setView([c.latitude, c.longitude], 14)
  }, [selectedId])

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