"use client";

import { useEffect, useMemo, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import useSWR from "swr";

type LiveEmployee = {
  employeeId: string;
  employeeCode: string;
  name: string;
  latitude: number;
  longitude: number;
  speed: number | null;
  timestamp: string;
  online: boolean;
  working: boolean;
  emergency: boolean;
  batteryLevel: number | null;
};

const fetcher = (url: string) => fetch(url).then((r) => r.json());

function markerIcon(emp: LiveEmployee) {
  const color = emp.emergency ? "#ef4444" : emp.online ? "#22c55e" : "#64748b";
  return L.divIcon({
    className: "",
    html: `<div style="width:14px;height:14px;border-radius:50%;background:${color};border:2px solid white;box-shadow:0 0 0 2px rgba(0,0,0,0.3)"></div>`,
    iconSize: [14, 14],
    iconAnchor: [7, 7],
  });
}

export default function LiveMap() {
  const [mapConfig, setMapConfig] = useState<{
    tileUrl: string | null;
    configured: boolean;
  } | null>(null);

  useEffect(() => {
    fetch("/api/map/config")
      .then((r) => r.json())
      .then(setMapConfig)
      .catch(() => setMapConfig({ tileUrl: null, configured: false }));
  }, []);

  const { data } = useSWR<{ employees: LiveEmployee[] }>("/api/location/live", fetcher, {
    refreshInterval: 5000,
  });

  const employees = data?.employees ?? [];
  const center = useMemo<[number, number]>(() => {
    if (employees.length > 0) return [employees[0].latitude, employees[0].longitude];
    return [23.8103, 90.4125]; // Dhaka, Bangladesh fallback
  }, [employees]);

  if (mapConfig && !mapConfig.configured) {
    return (
      <div className="flex items-center justify-center h-full text-slate-400 text-sm">
        Barikoi API key is not configured yet. Add it in Settings to enable the live map.
      </div>
    );
  }

  if (!mapConfig) {
    return <div className="flex items-center justify-center h-full text-slate-400 text-sm">Loading map…</div>;
  }

  return (
    <MapContainer center={center} zoom={13} style={{ height: "100%", width: "100%" }}>
      <TileLayer
        url={mapConfig.tileUrl!}
        attribution='&copy; <a href="https://barikoi.com">Barikoi</a>'
      />
      {employees.map((emp) => (
        <Marker key={emp.employeeId} position={[emp.latitude, emp.longitude]} icon={markerIcon(emp)}>
          <Popup>
            <div className="text-sm">
              <div className="font-medium">{emp.name}</div>
              <div className="text-xs text-slate-500">{emp.employeeCode}</div>
              <div className="mt-1">
                {emp.emergency ? "🚨 EMERGENCY" : emp.online ? "🟢 Online" : "⚪ Offline"}
              </div>
              <div>{emp.working ? "Working" : "Not in session"}</div>
              {emp.speed != null && <div>Speed: {(emp.speed * 3.6).toFixed(1)} km/h</div>}
              {emp.batteryLevel != null && <div>Battery: {emp.batteryLevel}%</div>}
              <div className="text-xs text-slate-500">
                Updated {new Date(emp.timestamp).toLocaleTimeString()}
              </div>
            </div>
          </Popup>
        </Marker>
      ))}
    </MapContainer>
  );
}
