/**
 * Video Chat Overlay Component
 * UI overlay for WebRTC video chat with controls and participant views
 */

import { Component, createSignal, onMount, Show } from 'solid-js';
import { WebRTCVideoManager, ConnectionQuality } from '../../lib/video/webrtc-video-manager';

export interface VideoChatOverlayProps {
  videoManager: WebRTCVideoManager;
  remotePeerId?: string;
  className?: string;
  showControls?: boolean;
}

export const VideoChatOverlay: Component<VideoChatOverlayProps> = (props) => {
  let localVideoRef: HTMLVideoElement | undefined;
  let remoteVideoRef: HTMLVideoElement | undefined;
  
  const [isAudioMuted, setIsAudioMuted] = createSignal(false);
  const [isVideoOff, setIsVideoOff] = createSignal(false);
  const [connectionQuality, setConnectionQuality] = createSignal<ConnectionQuality>('fair');
  const [isConnected, setIsConnected] = createSignal(false);

  const onMountCleanup = onMount(() => {
    const videoManager = props.videoManager;

    const localStream = videoManager.getLocalStream();
    if (localStream && localVideoRef) {
      localVideoRef.srcObject = localStream;
    }

    const handleLocalStream = (stream: MediaStream) => {
      if (localVideoRef) {
        localVideoRef.srcObject = stream;
      }
    };

    const handlePeerConnected = (peerId: string, stream: MediaStream) => {
      setIsConnected(true);
      if (props.remotePeerId === peerId && remoteVideoRef) {
        remoteVideoRef.srcObject = stream;
      }
    };

    const handlePeerDisconnected = (peerId: string) => {
      if (props.remotePeerId === peerId) {
        setIsConnected(false);
      }
    };

    const handleConnectionQuality = (peerId: string, quality: ConnectionQuality) => {
      if (props.remotePeerId === peerId) {
        setConnectionQuality(quality);
      }
    };

    videoManager.on('local:stream', handleLocalStream);
    videoManager.on('peer:connected', handlePeerConnected);
    videoManager.on('peer:disconnected', handlePeerDisconnected);
    videoManager.on('connection:quality', handleConnectionQuality);

    if (props.remotePeerId) {
      videoManager.connectToPeer(props.remotePeerId);
    }

    return () => {
      videoManager.off('local:stream', handleLocalStream);
      videoManager.off('peer:connected', handlePeerConnected);
      videoManager.off('peer:disconnected', handlePeerDisconnected);
      videoManager.off('connection:quality', handleConnectionQuality);
    };
  });

  const handleToggleAudio = () => {
    props.videoManager.toggleAudio();
    setIsAudioMuted(!props.videoManager.isAudioEnabled());
  };

  const handleToggleVideo = () => {
    props.videoManager.toggleVideo();
    setIsVideoOff(!props.videoManager.isVideoEnabled());
  };

  const handleHangup = () => {
    if (props.remotePeerId) {
      props.videoManager.disconnectFromPeer(props.remotePeerId);
      setIsConnected(false);
    }
  };

  const getConnectionQualityIndicator = (quality: ConnectionQuality): string => {
    switch (quality) {
      case 'excellent':
      case 'good':
        return '#22c55e';
      case 'fair':
        return '#eab308';
      case 'poor':
        return '#ef4444';
      default:
        return '#94a3b8';
    }
  };

  return (
    <div
      class={props.className || 'video-chat-overlay'}
      style={{
        display: 'flex',
        flexDirection: 'column',
        gap: '12px',
        width: '100%',
        maxWidth: '800px',
        margin: '0 auto',
      }}
    >
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: props.remotePeerId ? '1fr 1fr' : '1fr',
          gap: '8px',
        }}
      >
        <div
          style={{
            position: 'relative',
            backgroundColor: '#1e293b',
            borderRadius: '8px',
            overflow: 'hidden',
            aspectRatio: '16/9',
          }}
        >
          <video
            ref={localVideoRef}
            autoplay
            muted
            playsinline
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
            }}
          />
          <div
            style={{
              position: 'absolute',
              bottom: '8px',
              left: '8px',
              backgroundColor: 'rgba(0, 0, 0, 0.6)',
              color: 'white',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px',
            }}
          >
            You
          </div>
        </div>

        <Show when={props.remotePeerId && isConnected()}>
          <div
            style={{
              position: 'relative',
              backgroundColor: '#1e293b',
              borderRadius: '8px',
              overflow: 'hidden',
              aspectRatio: '16/9',
            }}
          >
            <video
              ref={remoteVideoRef}
              autoplay
              playsinline
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
            />
            <div
              style={{
                position: 'absolute',
                bottom: '8px',
                left: '8px',
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                color: 'white',
                padding: '4px 8px',
                borderRadius: '4px',
                fontSize: '12px',
              }}
            >
              Remote
            </div>
            <div
              style={{
                position: 'absolute',
                top: '8px',
                right: '8px',
                display: 'flex',
                alignItems: 'center',
                gap: '4px',
                backgroundColor: `${getConnectionQualityIndicator(connectionQuality())}20`,
                padding: '4px 8px',
                borderRadius: '4px',
                fontSize: '12px',
              }}
            >
              <span
                style={{
                  width: '8px',
                  height: '8px',
                  borderRadius: '50%',
                  backgroundColor: connectionQuality(),
                }}
              />
              {connectionQuality()}
            </div>
          </div>
        </Show>
      </div>

      <Show when={props.showControls}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            gap: '8px',
            padding: '12px',
            backgroundColor: '#f1f5f9',
            borderRadius: '8px',
          }}
        >
          <button
            onClick={handleToggleAudio}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '8px 16px',
              borderRadius: '6px',
              border: 'none',
              backgroundColor: isAudioMuted() ? '#ef4444' : '#22c55e',
              color: 'white',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: '500',
            }}
          >
            {isAudioMuted() ? '🔇' : '🎤'}
            {isAudioMuted() ? 'Unmute' : 'Mute'}
          </button>

          <button
            onClick={handleToggleVideo}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '8px 16px',
              borderRadius: '6px',
              border: 'none',
              backgroundColor: isVideoOff() ? '#ef4444' : '#22c55e',
              color: 'white',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: '500',
            }}
          >
            {isVideoOff() ? '📹' : '🎥'}
            {isVideoOff() ? 'Turn On' : 'Off'}
          </button>

          <Show when={isConnected()}>
            <button
              onClick={handleHangup}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '6px',
                padding: '8px 16px',
                borderRadius: '6px',
                border: 'none',
                backgroundColor: '#ef4444',
                color: 'white',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: '500',
              }}
            >
              📞 Hangup
            </button>
          </Show>
        </div>
      </Show>
    </div>
  );
};

export default VideoChatOverlay;
