"use client";

import { useEffect, useState } from "react";
import type { LatLngExpression } from "leaflet";

type Marker = {
  id: number;
  name: string;
  category: string;
  lat: number;
  lng: number;
};

export function ContractorsMap({ markers }: { markers: Marker[] }) {
  const [MapView, setMapView] = useState<React.ReactNode>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const L = await import("leaflet");
      await import("leaflet/dist/leaflet.css");
      const { MapContainer, TileLayer, Marker: LM, Popup } = await import(
        "react-leaflet"
      );

      // Fix default marker icons in bundlers
      // @ts-expect-error leaflet icon patch
      delete L.Icon.Default.prototype._getIconUrl;
      L.Icon.Default.mergeOptions({
        iconRetinaUrl:
          "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
        iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
        shadowUrl:
          "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
      });

      const center: LatLngExpression = markers[0]
        ? [markers[0].lat, markers[0].lng]
        : [18.2208, -66.5901];

      if (cancelled) return;
      setMapView(
        <MapContainer
          center={center}
          zoom={9}
          style={{ height: "100%", width: "100%", borderRadius: "1rem" }}
          scrollWheelZoom={false}
        >
          <TileLayer
            attribution='&copy; <a href="https://carto.com/">CARTO</a>'
            url="https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
          />
          {markers.map((m) => (
            <LM key={m.id} position={[m.lat, m.lng]}>
              <Popup>
                <strong>{m.name}</strong>
                <br />
                {m.category}
              </Popup>
            </LM>
          ))}
        </MapContainer>
      );
    })();
    return () => {
      cancelled = true;
    };
  }, [markers]);

  return (
    <div className="h-80 w-full overflow-hidden rounded-2xl border border-white/10 bg-[var(--surface)]">
      {MapView || (
        <div className="grid h-full place-items-center text-sm text-white/50">
          Cargando mapa…
        </div>
      )}
    </div>
  );
}
