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

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 VideoModal({ camera, onClose }) {
  const mapContainerRef = useRef(null);
  const mapRef = useRef(null);

  useEffect(() => {
    if (!camera) return;

    // Escape key handler
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        onClose && onClose();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [camera, onClose]);

  // Initialize mini map in modal
  useEffect(() => {
    if (!mapContainerRef.current || !camera) return;
    if (mapRef.current) return;

    const lng = Number(camera.lng);
    const lat = Number(camera.lat);
    if (!Number.isFinite(lng) || !Number.isFinite(lat)) return;

    const map = new maplibregl.Map({
      container: mapContainerRef.current,
      style: `https://api.maptiler.com/maps/streets-v2-dark/style.json?key=${MAPTILER_KEY}`,
      center: [lng, lat],
      zoom: 12,
      attributionControl: false,
      interactive: true,
    });

    // Add marker for camera
    const el = document.createElement("div");
    el.className = "sw-camera-marker is-selected";
    el.innerHTML = `<i class="fa-solid fa-video"></i>`;

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

    mapRef.current = map;

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

  if (!camera) return null;

  const name = camera.name_fr || camera.name_en || "Camera";
  const region = formatRegionLabel(camera.region);
  const route = camera.route || "";
  const embedUrl = (camera.embed_url || "").toString().trim();
  const videoUrl = (camera.video_url || "").toString().trim();
  const lat = camera.lat;
  const lng = camera.lng;

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose && onClose();
    }
  };

  const handleShare = () => {
    const shareUrl = embedUrl || videoUrl || "";
    if (navigator.share) {
      navigator.share({ title: name, text: `Live camera: ${name}`, url: shareUrl }).catch(() => {});
    } else if (navigator.clipboard && shareUrl) {
      navigator.clipboard.writeText(shareUrl);
    }
  };

  const handleOpenExternal = () => {
    const url = embedUrl || videoUrl;
    if (url) {
      window.open(url, "_blank", "noopener,noreferrer");
    }
  };

  return (
    <div className="sw-video-modal-backdrop" onClick={handleBackdropClick}>
      <div className="sw-video-modal">
        {/* Header */}
        <div className="sw-video-modal-header">
          <div className="sw-video-modal-avatar">
            <i className="fa-solid fa-video" />
          </div>
          <div className="sw-video-modal-meta">
            <div className="sw-video-modal-title">{name}</div>
            <div className="sw-video-modal-subtitle">
              {region}
              {route ? ` • Route ${route}` : ""}
            </div>
          </div>
          <div className="sw-video-modal-live-badge">
            <span className="sw-camera-dot" />
            <span>LIVE</span>
          </div>
          <button
            type="button"
            className="sw-video-modal-close"
            onClick={onClose}
            aria-label="Close"
          >
            <i className="fa-solid fa-times" />
          </button>
        </div>

        {/* Video Player */}
        <div className="sw-video-modal-content">
          <div className="sw-video-player">
            {embedUrl ? (
              <iframe
                src={embedUrl}
                title={name}
                allow="autoplay; encrypted-media"
                allowFullScreen
              />
            ) : videoUrl ? (
              <video
                src={videoUrl}
                autoPlay
                muted
                playsInline
                controls
                style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}
              />
            ) : (
              <div className="sw-video-player-fallback">
                <i className="fa-solid fa-video-slash" />
                <span>Stream unavailable</span>
                {camera.video_url && (
                  <a
                    href={camera.video_url}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    Open direct link
                  </a>
                )}
              </div>
            )}
          </div>

          {/* Location Info with Mini Map */}
          <div className="sw-video-modal-info">
            <div className="sw-video-modal-location">
              <i className="fa-solid fa-map-marker-alt" />
              <span>{region}</span>
              {lat && lng && (
                <span style={{ opacity: 0.7, fontSize: "0.75rem" }}>
                  ({Number(lat).toFixed(4)}, {Number(lng).toFixed(4)})
                </span>
              )}
            </div>
            <div ref={mapContainerRef} className="sw-video-modal-map" />
          </div>

          {/* Actions */}
          <div className="sw-video-modal-actions">
            <button type="button" className="sw-wall-btn" onClick={handleShare}>
              <i className="fa-solid fa-share-nodes" /> Share
            </button>
            <button type="button" className="sw-wall-btn" onClick={handleOpenExternal}>
              <i className="fa-solid fa-external-link" /> Open External
            </button>
            {camera.video_url && (
              <a
                href={camera.video_url}
                target="_blank"
                rel="noopener noreferrer"
                className="sw-wall-btn"
                style={{ textDecoration: "none" }}
              >
                <i className="fa-solid fa-link" /> Direct Stream
              </a>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
