"use client";

import { useEffect, useMemo, useState } from "react";
import {
  MapContainer,
  Marker,
  Polygon,
  Popup,
  TileLayer,
  useMap,
} from "react-leaflet";
import L from "leaflet";
import type { Site, VehicleMaster } from "@/lib/fleet/types";
import { getVehicleLatLng, isStale } from "@/lib/fleet/geo";
import { EVENING_THRESHOLDS } from "@/lib/fleet/evening";
import Link from "next/link";

const markerIcon = L.divIcon({
  className: "",
  html: `<span style="display:block;width:12px;height:12px;border-radius:999px;background:#1b2a4a;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.35)"></span>`,
  iconSize: [12, 12],
  iconAnchor: [6, 6],
});

const staleIcon = L.divIcon({
  className: "",
  html: `<span style="display:block;width:12px;height:12px;border-radius:999px;background:#9a6700;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.35)"></span>`,
  iconSize: [12, 12],
  iconAnchor: [6, 6],
});

function FitBounds({
  vehicles,
  sites,
}: {
  vehicles: VehicleMaster[];
  sites: Site[];
}) {
  const map = useMap();
  useEffect(() => {
    const points: [number, number][] = [];
    for (const v of vehicles) {
      if (isStale(v.location.properties.timestamp, EVENING_THRESHOLDS.staleMinutes)) {
        continue;
      }
      const { lat, lng } = getVehicleLatLng(v);
      points.push([lat, lng]);
    }
    for (const s of sites) {
      points.push([s.center.latitude, s.center.longitude]);
    }
    if (points.length) {
      map.fitBounds(points, { padding: [28, 28], maxZoom: 14 });
    }
  }, [map, vehicles, sites]);
  return null;
}

export function FleetMap({
  vehicles,
  sites,
  height = 360,
}: {
  vehicles: VehicleMaster[];
  sites: Site[];
  height?: number;
}) {
  const [ready, setReady] = useState(false);
  useEffect(() => setReady(true), []);

  const center = useMemo(() => {
    const s = sites[0];
    return {
      lat: s?.center.latitude ?? 48.14,
      lng: s?.center.longitude ?? 11.55,
    };
  }, [sites]);

  if (!ready) {
    return (
      <div
        className="flex items-center justify-center rounded-sm border border-[var(--line)] bg-[var(--surface)] text-sm text-[var(--muted)]"
        style={{ height }}
      >
        Karte wird geladen…
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-sm border border-[var(--line)]" style={{ height }}>
      <MapContainer
        center={[center.lat, center.lng]}
        zoom={12}
        style={{ height: "100%", width: "100%" }}
        scrollWheelZoom={false}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a>'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        {sites.flatMap((site) =>
          site.zones.map((zone) => (
            <Polygon
              key={`${site.id}-${zone.id}`}
              positions={zone.polygon}
              pathOptions={{
                color: "#1b2a4a",
                weight: 1,
                fillColor: "#1b2a4a",
                fillOpacity: 0.12,
              }}
            >
              <Popup>
                {site.shortName} · {zone.name}
              </Popup>
            </Polygon>
          )),
        )}
        {vehicles.map((v) => {
          const stale = isStale(
            v.location.properties.timestamp,
            EVENING_THRESHOLDS.staleMinutes,
          );
          if (stale) return null;
          const { lat, lng } = getVehicleLatLng(v);
          return (
            <Marker
              key={v.vin}
              position={[lat, lng]}
              icon={stale ? staleIcon : markerIcon}
            >
              <Popup>
                <div className="text-sm">
                  <strong>{v.licensePlate}</strong>
                  <div>{v.model}</div>
                  <Link href={`/fahrzeuge/${v.vin}`}>Zur Akte →</Link>
                </div>
              </Popup>
            </Marker>
          );
        })}
        <FitBounds vehicles={vehicles} sites={sites} />
      </MapContainer>
    </div>
  );
}
