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

const MAPTILER_KEY = "DvwhzlPmC55ZK28nLtXL";

/**
 * LiveViewerModal - Viewer UI for watching live streams
 *
 * Features:
 * - Main video + presenter PiP
 * - Participant grid
 * - Request to join
 * - Viewer count
 * - Location mini-map
 * - Share
 */
export default function LiveViewerModal({ streamID, streamData, onClose }) {
  const { username, token, authenticated } = useAuth();
  const userID = username || `viewer_${Date.now()}`;

  // Video refs
  const mainVideoRef = useRef(null);
  const presenterVideoRef = useRef(null);
  const localVideoRef = useRef(null);
  const participantRefs = useRef({});
  const mapContainerRef = useRef(null);
  const mapRef = useRef(null);

  // Viewer hook
  const {
    isConnected,
    isConnecting,
    error,
    mainStream,
    presenterStream,
    participantStreams,
    streamInfo,
    viewerCount,
    joinRequestStatus,
    isParticipant,
    localStream,
    connect,
    disconnect,
    requestToJoin,
    cancelJoinRequest,
    leaveAsParticipant,
  } = useWebRTCViewer({ streamID, userID, username, token });

  // Connect on mount
  useEffect(() => {
    connect();
    return () => {
      disconnect();
    };
  }, []);

  // Attach main stream
  useEffect(() => {
    if (mainVideoRef.current && mainStream) {
      mainVideoRef.current.srcObject = mainStream;
    }
  }, [mainStream]);

  // Attach presenter stream to PiP
  useEffect(() => {
    if (presenterVideoRef.current && presenterStream) {
      presenterVideoRef.current.srcObject = presenterStream;
    }
  }, [presenterStream]);

  // Attach local stream when participating
  useEffect(() => {
    if (localVideoRef.current && localStream) {
      localVideoRef.current.srcObject = localStream;
    }
  }, [localStream]);

  // Attach participant streams
  useEffect(() => {
    participantStreams.forEach((p) => {
      const ref = participantRefs.current[p.userID];
      if (ref && p.stream) {
        ref.srcObject = p.stream;
      }
    });
  }, [participantStreams]);

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

    const lat = streamData?.lat || streamInfo?.lat;
    const lng = streamData?.lon || streamInfo?.lon;

    if (!lat || !lng) 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: false,
    });

    // Add marker
    const el = document.createElement("div");
    el.className = "sw-live-marker";
    el.innerHTML = `<i class="fa-solid fa-broadcast-tower"></i>`;

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

    mapRef.current = map;

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

  const handleShare = useCallback(() => {
    const shareUrl = `${window.location.origin}/live/${streamID}`;
    if (navigator.share) {
      navigator.share({
        title: streamInfo?.title || "Live Stream",
        text: "Watch this live stream!",
        url: shareUrl,
      }).catch(() => {});
    } else if (navigator.clipboard) {
      navigator.clipboard.writeText(shareUrl);
      // Could show toast here
    }
  }, [streamID, streamInfo]);

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

  const handleClose = () => {
    disconnect();
    onClose?.();
  };

  const info = streamInfo || streamData || {};

  return (
    <div className="sw-viewer-modal" onClick={handleBackdropClick}>
      <div className="sw-viewer-container">
        {/* Header */}
        <div className="sw-viewer-header">
          <div className="sw-viewer-header-left">
            <div className="sw-viewer-live-badge">
              <span className="sw-viewer-dot" />
              <span>LIVE</span>
            </div>
            <span className="sw-viewer-title">{info.title || "Live Stream"}</span>
          </div>
          <div className="sw-viewer-header-right">
            <span className="sw-viewer-count">
              <i className="fa-solid fa-eye" /> {viewerCount}
            </span>
            <button
              type="button"
              className="sw-viewer-close"
              onClick={handleClose}
              aria-label="Close"
            >
              <i className="fa-solid fa-times" />
            </button>
          </div>
        </div>

        {/* Main content */}
        <div className="sw-viewer-content">
          {/* Video area */}
          <div className="sw-viewer-video-area">
            {/* Main video */}
            <div className="sw-viewer-main-video">
              {isConnecting ? (
                <div className="sw-viewer-video-placeholder">
                  <i className="fa-solid fa-spinner fa-spin" />
                  <span>Connecting...</span>
                </div>
              ) : error ? (
                <div className="sw-viewer-video-placeholder error">
                  <i className="fa-solid fa-exclamation-triangle" />
                  <span>{error}</span>
                </div>
              ) : mainStream ? (
                <video
                  ref={mainVideoRef}
                  autoPlay
                  playsInline
                  className="sw-viewer-video"
                />
              ) : (
                <div className="sw-viewer-video-placeholder">
                  <i className="fa-solid fa-video" />
                  <span>Waiting for stream...</span>
                </div>
              )}

              {/* Presenter PiP */}
              {presenterStream && (
                <div className="sw-viewer-pip">
                  <video
                    ref={presenterVideoRef}
                    autoPlay
                    playsInline
                    muted
                    className="sw-viewer-pip-video"
                  />
                </div>
              )}

              {/* Participant strip */}
              {participantStreams.length > 0 && (
                <div className="sw-viewer-participants-strip">
                  {participantStreams.map((p) => (
                    <div key={p.userID} className="sw-viewer-participant">
                      <video
                        ref={(el) => {
                          participantRefs.current[p.userID] = el;
                        }}
                        autoPlay
                        playsInline
                        className="sw-viewer-participant-video"
                      />
                      <div className="sw-viewer-participant-name">{p.username}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Self view when participating */}
              {isParticipant && localStream && (
                <div className="sw-viewer-self-pip">
                  <video
                    ref={localVideoRef}
                    autoPlay
                    playsInline
                    muted
                    className="sw-viewer-pip-video"
                  />
                  <div className="sw-viewer-pip-label">You</div>
                </div>
              )}
            </div>
          </div>

          {/* Side panel */}
          <div className="sw-viewer-side">
            {/* Stream info */}
            <div className="sw-viewer-info">
              <div className="sw-viewer-host">
                <i className="fa-solid fa-user" />
                <span>{info.broadcaster_name || "Host"}</span>
              </div>
              {info.title && <p className="sw-viewer-description">{info.title}</p>}
            </div>

            {/* Mini map */}
            <div ref={mapContainerRef} className="sw-viewer-map" />

            {/* Join section */}
            {authenticated && !isParticipant && (
              <div className="sw-viewer-join-section">
                {joinRequestStatus === null && (
                  <button
                    type="button"
                    className="sw-viewer-btn primary"
                    onClick={requestToJoin}
                  >
                    <i className="fa-solid fa-hand" />
                    <span>Request to Join</span>
                  </button>
                )}
                {joinRequestStatus === "pending" && (
                  <div className="sw-viewer-join-pending">
                    <i className="fa-solid fa-clock" />
                    <span>Waiting for host approval...</span>
                    <button
                      type="button"
                      className="sw-viewer-btn-small"
                      onClick={cancelJoinRequest}
                    >
                      Cancel
                    </button>
                  </div>
                )}
                {joinRequestStatus === "denied" && (
                  <div className="sw-viewer-join-denied">
                    <i className="fa-solid fa-times-circle" />
                    <span>Join request denied</span>
                  </div>
                )}
              </div>
            )}

            {/* Leave participant button */}
            {isParticipant && (
              <div className="sw-viewer-participant-controls">
                <button
                  type="button"
                  className="sw-viewer-btn danger"
                  onClick={leaveAsParticipant}
                >
                  <i className="fa-solid fa-sign-out-alt" />
                  <span>Leave as Participant</span>
                </button>
              </div>
            )}

            {/* Actions */}
            <div className="sw-viewer-actions">
              <button
                type="button"
                className="sw-viewer-action-btn"
                onClick={handleShare}
              >
                <i className="fa-solid fa-share-nodes" />
                <span>Share</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
