"use client";
import { useEffect } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { MapPin } from "lucide-react";

/* Fix Leaflet's broken default icon paths under webpack/Next.js */
delete (L.Icon.Default.prototype as { _getIconUrl?: unknown })._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 RED_PIN = L.divIcon({
  className: "",
  html: `
    <div style="
      display:flex;flex-direction:column;align-items:center;
      filter:drop-shadow(0 3px 6px rgba(0,0,0,0.30));
    ">
      <div style="
        width:32px;height:32px;border-radius:50% 50% 50% 0;
        background:#fc0000;transform:rotate(-45deg);
        display:flex;align-items:center;justify-content:center;
        border:2px solid white;
      ">
        <div style="
          width:10px;height:10px;border-radius:50%;
          background:rgba(255,255,255,0.9);transform:rotate(45deg);
        "></div>
      </div>
      <div style="
        width:10px;height:3px;background:rgba(0,0,0,0.18);
        border-radius:50%;filter:blur(1.5px);margin-top:1px;
      "></div>
    </div>`,
  iconSize: [32, 40],
  iconAnchor: [16, 40],
  popupAnchor: [0, -42],
});

/* Re-center map when props change */
function Recenter({ lat, lng }: { lat: number; lng: number }) {
  const map = useMap();
  useEffect(() => { map.setView([lat, lng], 14); }, [lat, lng, map]);
  return null;
}

export interface MarketplaceMapProps {
  lat: number;
  lng: number;
  area?: string;
  city?: string;
  pincode?: string;
}

export function MarketplaceMap({ lat, lng, area, city, pincode }: MarketplaceMapProps) {
  const label = [area, city].filter(Boolean).join(", ");

  if (!lat || !lng || isNaN(lat) || isNaN(lng)) {
    return (
      <div
        className="rounded-2xl flex flex-col items-center justify-center gap-2 border"
        style={{ height: 180, background: "var(--deep)", borderColor: "var(--border)" }}
      >
        <MapPin size={24} style={{ color: "var(--text-muted)" }} />
        <p className="text-xs" style={{ color: "var(--text-muted)" }}>Location unavailable</p>
      </div>
    );
  }

  return (
    <div
      className="rounded-2xl overflow-hidden border"
      style={{ borderColor: "var(--border)" }}
    >
      {/* Leaflet map */}
      <div style={{ height: 200, width: "100%" }}>
        <MapContainer
          center={[lat, lng]}
          zoom={14}
          scrollWheelZoom={false}
          style={{ height: "100%", width: "100%", zIndex: 0 }}
          attributionControl={false}
        >
          <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
          />
          <Recenter lat={lat} lng={lng} />
          <Marker position={[lat, lng]} icon={RED_PIN}>
            <Popup>
              <span style={{ fontWeight: 700, fontSize: 12 }}>{label}</span>
              {pincode && (
                <span style={{ fontSize: 11, color: "#666", display: "block" }}>
                  {pincode}
                </span>
              )}
            </Popup>
          </Marker>
        </MapContainer>
      </div>

      {/* Address footer */}
      <div
        className="flex items-center gap-2 px-4 py-3"
        style={{ background: "var(--card)", borderTop: "1px solid var(--border)" }}
      >
        <div
          className="w-6 h-6 rounded-full flex items-center justify-center shrink-0"
          style={{ background: "rgba(252,0,0,0.1)" }}
        >
          <MapPin size={12} style={{ color: "var(--accent)" }} />
        </div>
        <div>
          <p className="text-xs font-semibold" style={{ color: "var(--text-primary)" }}>
            {area}
          </p>
          <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
            {[city, pincode].filter(Boolean).join(" — ")}
          </p>
        </div>
        <span
          className="ml-auto text-[10px] font-bold px-2 py-0.5 rounded-full"
          style={{ background: "rgba(252,0,0,0.1)", color: "var(--accent)" }}
        >
          APPROX.
        </span>
      </div>

      {/* Leaflet default CSS overrides */}
      <style>{`
        .leaflet-container { font-family: inherit; }
        .leaflet-popup-content-wrapper {
          border-radius: 10px;
          box-shadow: 0 4px 16px rgba(0,0,0,0.15);
          padding: 0;
        }
        .leaflet-popup-content { margin: 10px 14px; }
        .leaflet-popup-tip-container { display: none; }
        .leaflet-control-zoom a {
          border-radius: 8px !important;
          font-size: 16px !important;
        }
      `}</style>
    </div>
  );
}
