"use client";

import { useState, useEffect } from "react";
import { MapContainer, TileLayer, Marker, useMapEvents } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { MapPin, Check, X } from "@phosphor-icons/react";
import type { PickedLocation } from "./LocationPicker";

// Fix Leaflet default icon in Next.js
delete (L.Icon.Default.prototype as unknown as Record<string, 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 pinIcon = L.divIcon({
  className: "",
  html: `<div style="
    width:28px;height:28px;
    background:var(--color-brand-yellow);
    border:3px solid var(--color-brand-dark);
    border-radius:50% 50% 50% 0;
    transform:rotate(-45deg);
    box-shadow:0 2px 8px rgba(0,0,0,0.35);
  "></div>`,
  iconSize:   [28, 28],
  iconAnchor: [14, 28],
});

function ClickHandler({ onPick }: { onPick: (lat: number, lng: number) => void }) {
  useMapEvents({
    click(e) { onPick(e.latlng.lat, e.latlng.lng); },
  });
  return null;
}

export default function LocationMapModal({
  initial,
  onConfirm,
  onClose,
}: {
  initial:   PickedLocation | null;
  onConfirm: (lat: number, lng: number) => Promise<void>;
  onClose:   () => void;
}) {
  const DEFAULT_CENTER: [number, number] = [18.0735, -15.9582]; // Nouakchott
  const [pin, setPin] = useState<[number, number] | null>(
    initial?.lat ? [initial.lat, initial.lng] : null
  );
  const [confirming, setConfirming] = useState(false);

  // Prevent body scroll while modal is open
  useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  const handleConfirm = async () => {
    if (!pin) return;
    setConfirming(true);
    await onConfirm(pin[0], pin[1]);
    setConfirming(false);
  };

  return (
    <div className="fixed inset-0 z-[200] flex flex-col bg-black/60 backdrop-blur-sm">

      {/* Header */}
      <div className="flex items-center justify-between bg-white px-4 py-3 shadow-sm flex-shrink-0">
        <div className="flex items-center gap-2">
          <MapPin size={18} weight="bold" className="text-brand-dark" />
          <span className="font-bold text-brand-dark text-sm">
            Choisir le lieu de livraison
          </span>
        </div>
        <button onClick={onClose} className="text-brand-dark/40 hover:text-brand-dark transition-colors">
          <X size={20} />
        </button>
      </div>

      {/* Hint */}
      <div className="bg-brand-yellow/90 px-4 py-2 text-brand-dark text-xs font-semibold text-center flex-shrink-0">
        Appuyez sur la carte pour placer l&apos;épingle
      </div>

      {/* Map */}
      <div className="flex-1 relative">
        <MapContainer
          center={pin ?? DEFAULT_CENTER}
          zoom={pin ? 14 : 12}
          style={{ width: "100%", height: "100%" }}
          zoomControl={true}
        >
          <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
          />
          <ClickHandler onPick={(lat, lng) => setPin([lat, lng])} />
          {pin && <Marker position={pin} icon={pinIcon} />}
        </MapContainer>
      </div>

      {/* Footer */}
      <div className="bg-white px-4 py-3 flex items-center gap-3 shadow-[0_-4px_20px_rgba(0,0,0,0.08)] flex-shrink-0">
        {pin ? (
          <p className="flex-1 text-brand-dark/60 text-xs truncate">
            {pin[0].toFixed(5)}, {pin[1].toFixed(5)}
          </p>
        ) : (
          <p className="flex-1 text-brand-dark/30 text-xs">Aucun point sélectionné</p>
        )}
        <button
          onClick={handleConfirm}
          disabled={!pin || confirming}
          className="flex items-center gap-2 bg-brand-dark text-brand-off-white font-bold px-5 py-2.5 rounded-full text-sm disabled:opacity-40 hover:bg-brand-dark/90 transition-all"
        >
          {confirming ? (
            <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
          ) : (
            <Check size={14} weight="bold" />
          )}
          {confirming ? "Enregistrement…" : "Confirmer"}
        </button>
      </div>
    </div>
  );
}
