"use client";

import { useEffect, useState } from "react";
import "leaflet/dist/leaflet.css";

export function PropertyMap({
  lat,
  lng,
  title,
}: {
  lat: number;
  lng: number;
  title: string;
}) {
  const [Leaflet, setLeaflet] =
    useState<null | typeof import("react-leaflet")>(null);

  useEffect(() => {
    let cancelled = false;
    Promise.all([import("react-leaflet"), import("leaflet")]).then(
      ([rl, L]) => {
        if (cancelled) return;
        // Fix default marker icon paths (Next bundler can't resolve them).
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        delete (L.Icon.Default.prototype as any)._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",
        });
        setLeaflet(rl);
      },
    );
    return () => {
      cancelled = true;
    };
  }, []);

  if (!Leaflet) {
    return (
      <div className="flex h-[320px] w-full items-center justify-center rounded-xl border border-zinc-200 bg-zinc-50 text-sm text-zinc-400">
        Loading map…
      </div>
    );
  }

  const { MapContainer, TileLayer, Marker } = Leaflet;
  return (
    <div className="overflow-hidden rounded-xl border border-zinc-200">
      <MapContainer
        center={[lat, lng]}
        zoom={14}
        scrollWheelZoom={false}
        style={{ height: "320px", width: "100%" }}
      >
        <TileLayer
          attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[lat, lng]} title={title} />
      </MapContainer>
    </div>
  );
}
