/**
 * LiveStreamPlayer Component
 * Live streaming player with chat and interaction features
 * Epic: OQI-002 Modulo Educativo
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';
import {
  PlayIcon,
  PauseIcon,
  SpeakerWaveIcon,
  SpeakerXMarkIcon,
  ArrowsPointingOutIcon,
  ArrowsPointingInIcon,
  SignalIcon,
  UsersIcon,
  ChatBubbleLeftRightIcon,
  HandRaisedIcon,
  HeartIcon,
  PaperAirplaneIcon,
  Cog6ToothIcon,
  XMarkIcon,
  ExclamationCircleIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/solid';

// Types
export interface StreamInfo {
  id: string;
  title: string;
  instructorName: string;
  instructorAvatar?: string;
  status: 'live' | 'starting' | 'ended' | 'scheduled';
  viewerCount: number;
  startTime: Date;
  scheduledTime?: Date;
  quality: 'auto' | '1080p' | '720p' | '480p' | '360p';
  latency: number;
}

export interface ChatMessage {
  id: string;
  userId: string;
  userName: string;
  userAvatar?: string;
  message: string;
  timestamp: Date;
  type: 'message' | 'system' | 'question' | 'highlight';
  isInstructor?: boolean;
  isPinned?: boolean;
}

export interface StreamReaction {
  type: 'like' | 'love' | 'fire' | 'clap' | 'question';
  count: number;
}

interface LiveStreamPlayerProps {
  streamUrl: string;
  streamInfo: StreamInfo;
  chatMessages: ChatMessage[];
  reactions?: StreamReaction[];
  onSendMessage?: (message: string) => void;
  onRaiseHand?: () => void;
  onReaction?: (type: StreamReaction['type']) => void;
  onQualityChange?: (quality: StreamInfo['quality']) => void;
  onReportIssue?: () => void;
  isHandRaised?: boolean;
  isChatEnabled?: boolean;
  compact?: boolean;
}

const QUALITY_OPTIONS: { value: StreamInfo['quality']; label: string }[] = [
  { value: 'auto', label: 'Auto' },
  { value: '1080p', label: '1080p HD' },
  { value: '720p', label: '720p' },
  { value: '480p', label: '480p' },
  { value: '360p', label: '360p' },
];

const REACTION_EMOJIS: Record<StreamReaction['type'], string> = {
  like: '👍',
  love: '❤️',
  fire: '🔥',
  clap: '👏',
  question: '❓',
};

const LiveStreamPlayer: React.FC<LiveStreamPlayerProps> = ({
  streamUrl,
  streamInfo,
  chatMessages,
  reactions = [],
  onSendMessage,
  onRaiseHand,
  onReaction,
  onQualityChange,
  onReportIssue,
  isHandRaised = false,
  isChatEnabled = true,
  compact = false,
}) => {
  // Video state
  const videoRef = useRef<HTMLVideoElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [isPlaying, setIsPlaying] = useState(true);
  const [isMuted, setIsMuted] = useState(false);
  const [volume, setVolume] = useState(1);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const [showSettings, setShowSettings] = useState(false);
  const [showChat, setShowChat] = useState(true);
  const [chatInput, setChatInput] = useState('');
  const [connectionStatus, setConnectionStatus] = useState<'connected' | 'reconnecting' | 'disconnected'>('connected');

  // Auto-hide controls
  useEffect(() => {
    let timeout: ReturnType<typeof setTimeout>;
    const hideControls = () => {
      if (isPlaying && !showSettings) {
        timeout = setTimeout(() => setShowControls(false), 3000);
      }
    };
    hideControls();
    return () => clearTimeout(timeout);
  }, [isPlaying, showSettings, showControls]);

  // Auto-scroll chat
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [chatMessages]);

  // Handle play/pause
  const togglePlay = useCallback(() => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  }, [isPlaying]);

  // Handle mute
  const toggleMute = useCallback(() => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  }, [isMuted]);

  // Handle volume change
  const handleVolumeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    setVolume(newVolume);
    if (videoRef.current) {
      videoRef.current.volume = newVolume;
      setIsMuted(newVolume === 0);
    }
  }, []);

  // Handle fullscreen
  const toggleFullscreen = useCallback(() => {
    const container = videoRef.current?.parentElement?.parentElement;
    if (!container) return;

    if (!isFullscreen) {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
    setIsFullscreen(!isFullscreen);
  }, [isFullscreen]);

  // Handle send message
  const handleSendMessage = useCallback(() => {
    if (chatInput.trim() && onSendMessage) {
      onSendMessage(chatInput.trim());
      setChatInput('');
    }
  }, [chatInput, onSendMessage]);

  // Format time
  const formatTime = (date: Date): string => {
    return date.toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // Format duration since start
  const formatDuration = (startTime: Date): string => {
    const diff = Date.now() - startTime.getTime();
    const hours = Math.floor(diff / 3600000);
    const minutes = Math.floor((diff % 3600000) / 60000);
    const seconds = Math.floor((diff % 60000) / 1000);
    if (hours > 0) return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  // Get status badge
  const getStatusBadge = () => {
    switch (streamInfo.status) {
      case 'live':
        return (
          <span className="flex items-center gap-1 px-2 py-1 bg-red-500 text-white text-xs font-medium rounded">
            <span className="w-2 h-2 bg-white rounded-full animate-pulse" />
            LIVE
          </span>
        );
      case 'starting':
        return (
          <span className="flex items-center gap-1 px-2 py-1 bg-yellow-500 text-black text-xs font-medium rounded">
            <ArrowPathIcon className="w-3 h-3 animate-spin" />
            Starting
          </span>
        );
      case 'ended':
        return (
          <span className="px-2 py-1 bg-gray-500 text-white text-xs font-medium rounded">
            Ended
          </span>
        );
      case 'scheduled':
        return (
          <span className="px-2 py-1 bg-blue-500 text-white text-xs font-medium rounded">
            Scheduled
          </span>
        );
    }
  };

  return (
    <div className={`flex flex-col lg:flex-row gap-4 ${compact ? '' : ''}`}>
      {/* Video Player Section */}
      <div className="flex-1">
        <div
          className="relative bg-black rounded-lg overflow-hidden aspect-video group"
          onMouseMove={() => setShowControls(true)}
          onMouseLeave={() => isPlaying && setShowControls(false)}
        >
          {/* Video Element */}
          <video
            ref={videoRef}
            src={streamUrl}
            className="w-full h-full object-contain"
            autoPlay
            playsInline
            onClick={togglePlay}
          />

          {/* Status Overlay */}
          {streamInfo.status !== 'live' && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/70">
              {streamInfo.status === 'starting' && (
                <div className="text-center">
                  <ArrowPathIcon className="w-12 h-12 mx-auto text-white animate-spin mb-4" />
                  <p className="text-white text-lg">Stream starting soon...</p>
                </div>
              )}
              {streamInfo.status === 'ended' && (
                <div className="text-center">
                  <p className="text-white text-lg">Stream has ended</p>
                  <p className="text-gray-400 mt-2">Thank you for watching!</p>
                </div>
              )}
              {streamInfo.status === 'scheduled' && streamInfo.scheduledTime && (
                <div className="text-center">
                  <p className="text-white text-lg">Stream scheduled for</p>
                  <p className="text-blue-400 text-xl mt-2">
                    {streamInfo.scheduledTime.toLocaleString()}
                  </p>
                </div>
              )}
            </div>
          )}

          {/* Top Overlay */}
          <div
            className={`absolute top-0 left-0 right-0 p-4 bg-gradient-to-b from-black/70 to-transparent transition-opacity ${
              showControls ? 'opacity-100' : 'opacity-0'
            }`}
          >
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                {getStatusBadge()}
                <div className="flex items-center gap-2 text-white text-sm">
                  <UsersIcon className="w-4 h-4" />
                  <span>{streamInfo.viewerCount.toLocaleString()} watching</span>
                </div>
                {streamInfo.status === 'live' && (
                  <div className="text-gray-400 text-sm">
                    {formatDuration(streamInfo.startTime)}
                  </div>
                )}
              </div>

              {/* Connection Status */}
              {connectionStatus !== 'connected' && (
                <div
                  className={`flex items-center gap-1 px-2 py-1 rounded text-xs ${
                    connectionStatus === 'reconnecting'
                      ? 'bg-yellow-500/20 text-yellow-400'
                      : 'bg-red-500/20 text-red-400'
                  }`}
                >
                  <SignalIcon className="w-3 h-3" />
                  {connectionStatus === 'reconnecting' ? 'Reconnecting...' : 'Disconnected'}
                </div>
              )}
            </div>
          </div>

          {/* Bottom Controls */}
          <div
            className={`absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/70 to-transparent transition-opacity ${
              showControls ? 'opacity-100' : 'opacity-0'
            }`}
          >
            <div className="flex items-center gap-4">
              {/* Play/Pause */}
              <button
                onClick={togglePlay}
                className="text-white hover:text-blue-400 transition-colors"
              >
                {isPlaying ? (
                  <PauseIcon className="w-8 h-8" />
                ) : (
                  <PlayIcon className="w-8 h-8" />
                )}
              </button>

              {/* Volume */}
              <div className="flex items-center gap-2">
                <button onClick={toggleMute} className="text-white hover:text-blue-400">
                  {isMuted || volume === 0 ? (
                    <SpeakerXMarkIcon className="w-6 h-6" />
                  ) : (
                    <SpeakerWaveIcon className="w-6 h-6" />
                  )}
                </button>
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.1"
                  value={volume}
                  onChange={handleVolumeChange}
                  className="w-20 h-1 bg-gray-600 rounded-lg appearance-none cursor-pointer"
                />
              </div>

              <div className="flex-1" />

              {/* Latency Indicator */}
              <div className="flex items-center gap-1 text-gray-400 text-xs">
                <SignalIcon className="w-3 h-3" />
                <span>{streamInfo.latency}ms</span>
              </div>

              {/* Quality Selector */}
              <select
                value={streamInfo.quality}
                onChange={(e) => onQualityChange?.(e.target.value as StreamInfo['quality'])}
                className="bg-transparent text-white text-sm border border-gray-600 rounded px-2 py-1"
              >
                {QUALITY_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value} className="bg-gray-800">
                    {opt.label}
                  </option>
                ))}
              </select>

              {/* Settings */}
              <button
                onClick={() => setShowSettings(!showSettings)}
                className="text-white hover:text-blue-400 transition-colors"
              >
                <Cog6ToothIcon className="w-6 h-6" />
              </button>

              {/* Fullscreen */}
              <button
                onClick={toggleFullscreen}
                className="text-white hover:text-blue-400 transition-colors"
              >
                {isFullscreen ? (
                  <ArrowsPointingInIcon className="w-6 h-6" />
                ) : (
                  <ArrowsPointingOutIcon className="w-6 h-6" />
                )}
              </button>
            </div>
          </div>

          {/* Floating Reactions */}
          {reactions.length > 0 && (
            <div className="absolute bottom-20 right-4 flex flex-col gap-2">
              {reactions.map((reaction) => (
                <button
                  key={reaction.type}
                  onClick={() => onReaction?.(reaction.type)}
                  className="flex items-center gap-1 px-2 py-1 bg-black/50 rounded-full text-white text-sm hover:bg-black/70 transition-colors"
                >
                  <span>{REACTION_EMOJIS[reaction.type]}</span>
                  <span>{reaction.count}</span>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Stream Info */}
        <div className="mt-4 bg-gray-800/50 rounded-lg p-4 border border-gray-700">
          <h1 className="text-xl font-bold text-white">{streamInfo.title}</h1>
          <div className="flex items-center gap-4 mt-3">
            {streamInfo.instructorAvatar ? (
              <img
                src={streamInfo.instructorAvatar}
                alt={streamInfo.instructorName}
                className="w-10 h-10 rounded-full"
              />
            ) : (
              <div className="w-10 h-10 bg-gray-700 rounded-full flex items-center justify-center">
                <span className="text-white font-medium">
                  {streamInfo.instructorName.charAt(0)}
                </span>
              </div>
            )}
            <div>
              <p className="text-white font-medium">{streamInfo.instructorName}</p>
              <p className="text-gray-400 text-sm">Instructor</p>
            </div>

            <div className="flex-1" />

            {/* Action Buttons */}
            <div className="flex items-center gap-2">
              {onRaiseHand && (
                <button
                  onClick={onRaiseHand}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                    isHandRaised
                      ? 'bg-yellow-500 text-black'
                      : 'bg-gray-700 text-white hover:bg-gray-600'
                  }`}
                >
                  <HandRaisedIcon className="w-5 h-5" />
                  {isHandRaised ? 'Hand Raised' : 'Raise Hand'}
                </button>
              )}
              <button
                onClick={() => setShowChat(!showChat)}
                className={`p-2 rounded-lg transition-colors lg:hidden ${
                  showChat ? 'bg-blue-500 text-white' : 'bg-gray-700 text-white hover:bg-gray-600'
                }`}
              >
                <ChatBubbleLeftRightIcon className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Chat Section */}
      {showChat && isChatEnabled && (
        <div className="w-full lg:w-80 bg-gray-800/50 rounded-lg border border-gray-700 flex flex-col h-[500px] lg:h-auto">
          {/* Chat Header */}
          <div className="p-3 border-b border-gray-700 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ChatBubbleLeftRightIcon className="w-5 h-5 text-blue-400" />
              <span className="text-white font-medium">Live Chat</span>
            </div>
            <button
              onClick={() => setShowChat(false)}
              className="p-1 text-gray-400 hover:text-white lg:hidden"
            >
              <XMarkIcon className="w-5 h-5" />
            </button>
          </div>

          {/* Chat Messages */}
          <div ref={chatContainerRef} className="flex-1 overflow-y-auto p-3 space-y-3">
            {chatMessages.map((msg) => (
              <div
                key={msg.id}
                className={`${
                  msg.type === 'system'
                    ? 'text-center'
                    : msg.isPinned
                    ? 'bg-blue-500/10 border border-blue-500/30 rounded-lg p-2'
                    : ''
                }`}
              >
                {msg.type === 'system' ? (
                  <p className="text-gray-500 text-xs">{msg.message}</p>
                ) : (
                  <div className="flex items-start gap-2">
                    {msg.userAvatar ? (
                      <img
                        src={msg.userAvatar}
                        alt={msg.userName}
                        className="w-6 h-6 rounded-full flex-shrink-0"
                      />
                    ) : (
                      <div className="w-6 h-6 bg-gray-700 rounded-full flex items-center justify-center flex-shrink-0">
                        <span className="text-white text-xs">{msg.userName.charAt(0)}</span>
                      </div>
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span
                          className={`text-sm font-medium ${
                            msg.isInstructor ? 'text-blue-400' : 'text-gray-300'
                          }`}
                        >
                          {msg.userName}
                        </span>
                        {msg.isInstructor && (
                          <span className="px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] rounded">
                            Instructor
                          </span>
                        )}
                        <span className="text-gray-500 text-xs">{formatTime(msg.timestamp)}</span>
                      </div>
                      <p
                        className={`text-sm mt-0.5 break-words ${
                          msg.type === 'question' ? 'text-yellow-400' : 'text-white'
                        }`}
                      >
                        {msg.type === 'question' && '❓ '}
                        {msg.message}
                      </p>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Chat Input */}
          <div className="p-3 border-t border-gray-700">
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
                placeholder="Send a message..."
                className="flex-1 bg-gray-900/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
              />
              <button
                onClick={handleSendMessage}
                disabled={!chatInput.trim()}
                className="p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <PaperAirplaneIcon className="w-5 h-5" />
              </button>
            </div>

            {/* Quick Reactions */}
            <div className="flex items-center gap-1 mt-2">
              {Object.entries(REACTION_EMOJIS).map(([type, emoji]) => (
                <button
                  key={type}
                  onClick={() => onReaction?.(type as StreamReaction['type'])}
                  className="p-1.5 hover:bg-gray-700 rounded transition-colors text-lg"
                  title={type}
                >
                  {emoji}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default LiveStreamPlayer;
