"use client";

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

export interface Geofence {
  lat: number;
  lng: number;
  radiusM: number;
}

export interface Pt {
  lat: number;
  lng: number;
  recordedAt: string;
  battery: number | null;
  accuracy?: number | null;
}

function FitBounds({ points, geo }: { points: Pt[]; geo: Geofence | null }) {
  const map = useMap();
  const gLat = geo?.lat;
  const gLng = geo?.lng;
  useEffect(() => {
    const coords: [number, number][] = points.map((p) => [p.lat, p.lng]);
    if (gLat != null && gLng != null) coords.push([gLat, gLng]); // inclure le point de référence
    if (coords.length === 0) return;
    if (coords.length === 1) {
      map.setView(coords[0], 15);
      return;
    }
    const lats = coords.map((c) => c[0]);
    const lngs = coords.map((c) => c[1]);
    map.fitBounds(
      [
        [Math.min(...lats), Math.min(...lngs)],
        [Math.max(...lats), Math.max(...lngs)],
      ],
      { padding: [30, 30] }
    );
  }, [points, gLat, gLng, map]);
  return null;
}

// Mode "définir le point de référence" : capte le clic sur la carte.
function ClickPicker({ onPick }: { onPick: (lat: number, lng: number) => void }) {
  useMapEvents({
    click(e) {
      onPick(e.latlng.lat, e.latlng.lng);
    },
  });
  return null;
}

// Centre la carte sur un point choisi dans la liste d'historique.
function FocusController({ focus }: { focus: Pt | null }) {
  const map = useMap();
  useEffect(() => {
    if (focus) map.setView([focus.lat, focus.lng], 16);
  }, [focus, map]);
  return null;
}

export default function MapView({
  points,
  markers = [],
  focus = null,
  geofence = null,
  pickMode = false,
  onPick,
}: {
  points: Pt[]; // trace complète (polyline + dernière position)
  markers?: Pt[]; // marqueurs détaillés (page courante de l'historique)
  focus?: Pt | null;
  geofence?: Geofence | null; // zone d'alerte à afficher (cercle)
  pickMode?: boolean; // si vrai, un clic sur la carte définit le point de référence
  onPick?: (lat: number, lng: number) => void;
}) {
  const last = points[points.length - 1];
  const center: [number, number] = last ? [last.lat, last.lng] : [46.6, 2.5]; // France par défaut

  return (
    <MapContainer center={center} zoom={13} scrollWheelZoom className="relative z-0 isolate h-[60vh] w-full rounded-2xl">
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      {points.length > 1 && (
        <Polyline positions={points.map((p) => [p.lat, p.lng] as [number, number])} pathOptions={{ color: "#3b82f6", weight: 3 }} />
      )}
      {markers.map((p, i) => (
        <CircleMarker
          key={i}
          center={[p.lat, p.lng]}
          radius={4}
          pathOptions={{ color: "#93c5fd", fillColor: "#93c5fd", fillOpacity: 0.9 }}
        >
          <Popup>
            {new Date(p.recordedAt).toLocaleString("fr-FR")}
            {p.battery != null ? ` · 🔋 ${p.battery}%` : ""}
          </Popup>
        </CircleMarker>
      ))}
      {last && (
        <CircleMarker
          center={[last.lat, last.lng]}
          radius={8}
          pathOptions={{ color: "#2563eb", fillColor: "#2563eb", fillOpacity: 0.9 }}
        >
          <Popup>
            Dernière position · {new Date(last.recordedAt).toLocaleString("fr-FR")}
            {last.battery != null ? ` · 🔋 ${last.battery}%` : ""}
          </Popup>
        </CircleMarker>
      )}
      {focus && (
        <CircleMarker
          center={[focus.lat, focus.lng]}
          radius={11}
          pathOptions={{ color: "#dc2626", weight: 3, fillColor: "#dc2626", fillOpacity: 0.25 }}
        />
      )}
      {geofence && (
        <>
          <Circle
            center={[geofence.lat, geofence.lng]}
            radius={geofence.radiusM}
            pathOptions={{ color: "#16a34a", fillColor: "#16a34a", fillOpacity: 0.1 }}
          />
          <CircleMarker
            center={[geofence.lat, geofence.lng]}
            radius={5}
            pathOptions={{ color: "#16a34a", fillColor: "#16a34a", fillOpacity: 1 }}
          >
            <Popup>Point de référence ({geofence.radiusM} m)</Popup>
          </CircleMarker>
        </>
      )}
      {pickMode && onPick && <ClickPicker onPick={onPick} />}
      <FitBounds points={points} geo={geofence} />
      <FocusController focus={focus} />
    </MapContainer>
  );
}
