'use client'

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { Link } from '@/i18n/routing'

export interface MapListing {
  id: string
  slug: string
  name: string
  categorySlug: string
  categoryName: string
  latitude: number
  longitude: number
  isLocalApproved: boolean
  image?: string
}

function buildPinIcon(color: string) {
  return L.divIcon({
    className: '',
    html: `
      <svg width="28" height="36" viewBox="0 0 28 36" xmlns="http://www.w3.org/2000/svg">
        <path d="M14 0C6.3 0 0 6.3 0 14c0 10.5 14 22 14 22s14-11.5 14-22C28 6.3 21.7 0 14 0z" fill="${color}" stroke="#FBFAF6" stroke-width="1.5"/>
        <circle cx="14" cy="14" r="5" fill="#FBFAF6"/>
      </svg>
    `,
    iconSize: [28, 36],
    iconAnchor: [14, 34],
    popupAnchor: [0, -32],
  })
}

const approvedIcon = buildPinIcon('#E8A23D')
const defaultIcon = buildPinIcon('#2E9C9A')

interface ListingsMapProps {
  listings: MapListing[]
  approvedLabel: string
  viewLabel: string
}

export default function ListingsMap({ listings, approvedLabel, viewLabel }: ListingsMapProps) {
  if (listings.length === 0) return null

  const center: [number, number] = [
    listings.reduce((sum, l) => sum + l.latitude, 0) / listings.length,
    listings.reduce((sum, l) => sum + l.longitude, 0) / listings.length,
  ]

  return (
    <MapContainer
      center={center}
      zoom={13}
      scrollWheelZoom={false}
      className="w-full h-full"
      style={{ background: '#EDEEE3' }}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      {listings.map((listing) => (
        <Marker
          key={listing.id}
          position={[listing.latitude, listing.longitude]}
          icon={listing.isLocalApproved ? approvedIcon : defaultIcon}
        >
          <Popup>
            <div className="space-y-1.5 min-w-[160px]">
              {listing.isLocalApproved && (
                <span className="inline-block text-[10px] font-bold uppercase tracking-wider text-[#E8A23D]">
                  {approvedLabel}
                </span>
              )}
              <div className="font-semibold text-sm text-[#123238]">{listing.name}</div>
              <div className="text-xs text-[#4F7C93]">{listing.categoryName}</div>
              <Link
                href={`/${listing.categorySlug}/${listing.slug}`}
                className="inline-block text-xs font-semibold text-[#2E9C9A] hover:underline"
              >
                {viewLabel} →
              </Link>
            </div>
          </Popup>
        </Marker>
      ))}
    </MapContainer>
  )
}
