import { divIcon } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { MapContainer, Marker, TileLayer, Tooltip, useMapEvents } from 'react-leaflet';
import { cn } from '@/lib/cn';

/** Carte Leaflet/OSM (positions PostGIS) — pins au style de la maquette. */

export interface PinGeo {
  id: string;
  latitude: number;
  longitude: number;
  libelle: string;
  alerte?: boolean;
  onClick?: () => void;
}

const CENTRE_CASABLANCA: [number, number] = [33.59, -7.6];

function iconePin(alerte?: boolean) {
  return divIcon({
    className: '',
    html: `<div class="pin-geo${alerte ? ' alerte' : ''}"></div>`,
    iconSize: [26, 26],
    iconAnchor: [13, 26],
  });
}

function ClicCarte({ onClick }: { onClick?: (lat: number, lng: number) => void }) {
  useMapEvents({
    click(e) {
      onClick?.(Number(e.latlng.lat.toFixed(5)), Number(e.latlng.lng.toFixed(5)));
    },
  });
  return null;
}

export function CarteGeo({
  pins,
  className,
  zoom = 11,
  centre,
  onClick,
}: {
  pins: PinGeo[];
  className?: string;
  zoom?: number;
  centre?: [number, number];
  onClick?: (lat: number, lng: number) => void;
}) {
  const centreEffectif =
    centre ??
    (pins.length
      ? ([pins[0]!.latitude, pins[0]!.longitude] as [number, number])
      : CENTRE_CASABLANCA);

  return (
    <div className={cn('geo', className)}>
      <MapContainer center={centreEffectif} zoom={zoom} scrollWheelZoom={false}>
        <TileLayer
          attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
          url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <ClicCarte onClick={onClick} />
        {pins.map((pin) => (
          <Marker
            key={pin.id}
            position={[pin.latitude, pin.longitude]}
            icon={iconePin(pin.alerte)}
            eventHandlers={pin.onClick ? { click: pin.onClick } : undefined}
          >
            <Tooltip direction="bottom" offset={[0, 6]}>{pin.libelle}</Tooltip>
          </Marker>
        ))}
      </MapContainer>
    </div>
  );
}
