import React, { useCallback, useEffect, useRef, useState } from "react";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import "./Live.css";

const API_BASE = "/live/api";
const MAPTILER_KEY = "DvwhzlPmC55ZK28nLtXL";

function formatRegionLabel(region) {
  if (!region) return "Unknown";
  return region
    .replace(/_/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

export default function CameraMiniMap({
  region = null,
  limit = 50,
  height = 280,
  onCameraClick,
  selectedCameraId = null,
}) {
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef([]);
  const [cameras, setCameras] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Fetch cameras
  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);

    const url = region
      ? `${API_BASE}/cameras?region=${encodeURIComponent(region)}`
      : `${API_BASE}/cameras`;

    fetch(url)
      .then((res) => {
        if (!res.ok) throw new Error("Failed to fetch cameras");
        return res.json();
      })
      .then((data) => {
        if (cancelled) return;
        const cams = Array.isArray(data.cameras) ? data.cameras : [];
        setCameras(cams.slice(0, limit));
        setLoading(false);
      })
      .catch((err) => {
        if (cancelled) return;
        console.error("Camera fetch error:", err);
        setError(err.message || "Error loading cameras");
        setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [region, limit]);

  // Initialize map
  useEffect(() => {
    if (!containerRef.current || mapRef.current) return;

    const map = new maplibregl.Map({
      container: containerRef.current,
      style: `https://api.maptiler.com/maps/streets-v2-dark/style.json?key=${MAPTILER_KEY}`,
      center: [-71.2, 46.8], // Quebec City default
      zoom: 6,
      attributionControl: false,
    });

    map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-right");

    mapRef.current = map;

    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, []);

  // Add camera markers
  useEffect(() => {
    const map = mapRef.current;
    if (!map || !cameras.length) return;

    // Clear old markers
    markersRef.current.forEach((m) => m.remove());
    markersRef.current = [];

    // Calculate bounds
    const bounds = new maplibregl.LngLatBounds();

    cameras.forEach((cam) => {
      const lng = Number(cam.lng);
      const lat = Number(cam.lat);
      if (!Number.isFinite(lng) || !Number.isFinite(lat)) return;

      bounds.extend([lng, lat]);

      // Create marker element
      const el = document.createElement("div");
      el.className = "sw-camera-marker";
      if (selectedCameraId && cam.id === selectedCameraId) {
        el.classList.add("is-selected");
      }

      // Camera icon
      el.innerHTML = `<i class="fa-solid fa-video"></i>`;

      const marker = new maplibregl.Marker({ element: el })
        .setLngLat([lng, lat])
        .addTo(map);

      el.addEventListener("click", (e) => {
        e.stopPropagation();
        if (onCameraClick) onCameraClick(cam);
      });

      markersRef.current.push(marker);
    });

    // Fit bounds if we have cameras
    if (cameras.length > 0 && !bounds.isEmpty()) {
      const tryFit = () => {
        if (!map || !map.loaded()) return false;
        try {
          map.fitBounds(bounds, {
            padding: 40,
            maxZoom: 10,
            duration: 500,
          });
        } catch {}
        return true;
      };

      if (!tryFit()) {
        map.once("load", tryFit);
      }
    }

    return () => {
      markersRef.current.forEach((m) => m.remove());
      markersRef.current = [];
    };
  }, [cameras, selectedCameraId, onCameraClick]);

  return (
    <div className="sw-camera-minimap" style={{ height }}>
      <div className="sw-camera-minimap-header">
        <i className="fa-solid fa-video" />
        <span>Live Cameras</span>
        {region && <span className="sw-camera-region-badge">{formatRegionLabel(region)}</span>}
        <span className="sw-camera-count">{cameras.length}</span>
      </div>
      <div ref={containerRef} className="sw-camera-minimap-container" />
      {loading && (
        <div className="sw-camera-minimap-overlay">
          <div className="sw-camera-loader">
            <i className="fa-solid fa-spinner fa-spin" />
            <span>Loading cameras...</span>
          </div>
        </div>
      )}
      {error && (
        <div className="sw-camera-minimap-overlay sw-camera-error">
          <i className="fa-solid fa-exclamation-triangle" />
          <span>{error}</span>
        </div>
      )}
    </div>
  );
}
