"use client";

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

// Fix Leaflet default icon paths (broken by webpack)
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",
});

// Custom coloured icons
const pickupIcon = new L.Icon({
  iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
});

const dropoffIcon = new L.Icon({
  iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
});

// Auto-fit bounds to show both markers
function FitBounds({ positions }: { positions: [number, number][] }) {
  const map = useMap();
  useEffect(() => {
    if (positions.length >= 2) {
      map.fitBounds(L.latLngBounds(positions), { padding: [48, 48], maxZoom: 14 });
    } else if (positions.length === 1) {
      map.setView(positions[0], 14);
    }
  }, [positions, map]);
  return null;
}

interface RouteMapProps {
  pickup: { lat: number; lon: number; label: string } | null;
  dropoff: { lat: number; lon: number; label: string } | null;
  routeGeometry: GeoJSON.LineString | null;
}

export default function RouteMap({ pickup, dropoff, routeGeometry }: RouteMapProps) {
  const positions: [number, number][] = [];
  if (pickup) positions.push([pickup.lat, pickup.lon]);
  if (dropoff) positions.push([dropoff.lat, dropoff.lon]);

  // Convert GeoJSON coordinates [lon, lat] → Leaflet [lat, lon]
  const polylinePositions: [number, number][] =
    routeGeometry?.coordinates?.map(([lon, lat]: number[]) => [lat, lon]) ?? [];

  const center: [number, number] = positions[0] ?? [50.8503, 4.3517]; // Default: Brussels

  return (
    <MapContainer
      center={center}
      zoom={12}
      style={{ height: "320px", width: "100%", borderRadius: "12px" }}
      className="z-0"
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />

      {pickup && (
        <Marker position={[pickup.lat, pickup.lon]} icon={pickupIcon}>
          <Popup>
            <strong>Départ</strong>
            <br />
            {pickup.label}
          </Popup>
        </Marker>
      )}

      {dropoff && (
        <Marker position={[dropoff.lat, dropoff.lon]} icon={dropoffIcon}>
          <Popup>
            <strong>Arrivée</strong>
            <br />
            {dropoff.label}
          </Popup>
        </Marker>
      )}

      {polylinePositions.length > 0 && (
        <Polyline
          positions={polylinePositions}
          pathOptions={{ color: "#c5a880", weight: 4, opacity: 0.85 }}
        />
      )}

      <FitBounds positions={positions} />
    </MapContainer>
  );
}

