import { useState, useEffect, useRef } from 'react';
import { Crown, Users, Play, ArrowLeft, Copy, Check, QrCode, UserMinus } from 'lucide-react';
import QRCodeGenerator from './QRCodeGenerator';
import { GAME_MODES } from '../utils/gameUtils';

function Lobby({ socket, playerData, roomData, onLeaveRoom, onGameStart }) {
  const [copied, setCopied] = useState(false);
  const [showQRCode, setShowQRCode] = useState(false);
  
  // Game mode selection (host only)
  const [multiModeEnabled, setMultiModeEnabled] = useState(false);
  const [selectedSingleMode, setSelectedSingleMode] = useState('fullHouse');
  const [selectedMultiModes, setSelectedMultiModes] = useState({
    first: 'fullHouse',
    second: 'corners',
    third: 'earlyFive'
  });

  // HOST SUPERPOWERS - New state variables for lobby
  const [showPlayerManagement, setShowPlayerManagement] = useState(false);
  const [showTransferHost, setShowTransferHost] = useState(false);
  const [showKickConfirm, setShowKickConfirm] = useState(false);
  const [selectedPlayerToKick, setSelectedPlayerToKick] = useState(null);
  const [selectedPlayerForHost, setSelectedPlayerForHost] = useState(null);
  const [hostActionLoading, setHostActionLoading] = useState(false);
  
  // Ref for click outside detection
  const playerManagementRef = useRef(null);

  // Check if current player is host
  const isHost = roomData?.players?.find(p => p.id === playerData?.playerId)?.isHost;

  // HOST SUPERPOWERS - Functions for lobby
  const openKickConfirmation = (player) => {
    setSelectedPlayerToKick(player);
    setShowKickConfirm(true);
    setShowPlayerManagement(false);
  };

  const confirmKickPlayer = () => {
    if (!selectedPlayerToKick || !socket) return;
    
    setHostActionLoading(true);
    socket.emit('kickPlayer', { targetPlayerId: selectedPlayerToKick.id });
    
    setTimeout(() => {
      setHostActionLoading(false);
      setShowKickConfirm(false);
      setSelectedPlayerToKick(null);
    }, 1000);
  };

  const openTransferHostDialog = () => {
    setShowTransferHost(true);
    setShowPlayerManagement(false);
  };

  const confirmTransferHost = () => {
    if (!selectedPlayerForHost || !socket) return;
    
    setHostActionLoading(true);
    socket.emit('transferHost', { targetPlayerId: selectedPlayerForHost });
    
    setTimeout(() => {
      setHostActionLoading(false);
      setShowTransferHost(false);
      setSelectedPlayerForHost(null);
    }, 1000);
  };

  // Click outside to close dropdowns
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (playerManagementRef.current && !playerManagementRef.current.contains(event.target)) {
        setShowPlayerManagement(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Socket event listeners
  useEffect(() => {
    if (!socket) return;

    // Listen for game start events
    socket.on('gameStarted', (data) => {
      onGameStart(data.room);
    });

    socket.on('multiModeGameStarted', (data) => {
      onGameStart(data.room, data.activeGameModes);
    });

    // Listen for host's game mode selection updates
    socket.on('gameModeSelectionUpdated', (data) => {
      setMultiModeEnabled(data.multiModeEnabled);
      if (data.multiModeEnabled) {
        setSelectedMultiModes(data.selectedMultiModes);
      } else {
        setSelectedSingleMode(data.selectedSingleMode);
      }
    });

    // HOST SUPERPOWERS - Socket listeners for lobby
    socket.on('playerKicked', (data) => {
      // Handle being kicked
      if (playerData?.playerId === data.playerId) {
        onLeaveRoom();
      }
    });

    socket.on('hostTransferred', (data) => {
      // Handle host transfer notification - the roomData will be updated via other events
      console.log(`Host transferred from ${data.oldHost.nickname} to ${data.newHost.nickname}`);
    });

    return () => {
      socket.off('gameStarted');
      socket.off('multiModeGameStarted');
      socket.off('gameModeSelectionUpdated');
      socket.off('playerKicked');
      socket.off('hostTransferred');
    };
  }, [socket, onGameStart]);

  // Update game mode selection and broadcast changes
  const handleMultiModeToggle = (enabled) => {
    setMultiModeEnabled(enabled);
    if (isHost && socket) {
      socket.emit('updateGameModeSelection', {
        multiModeEnabled: enabled,
        selectedSingleMode,
        selectedMultiModes
      });
    }
  };

  const handleSingleModeChange = (mode) => {
    setSelectedSingleMode(mode);
    if (isHost && socket) {
      socket.emit('updateGameModeSelection', {
        multiModeEnabled,
        selectedSingleMode: mode,
        selectedMultiModes
      });
    }
  };

  const handleMultiModeChange = (position, mode) => {
    const newMultiModes = {
      ...selectedMultiModes,
      [position]: mode
    };
    setSelectedMultiModes(newMultiModes);
    if (isHost && socket) {
      socket.emit('updateGameModeSelection', {
        multiModeEnabled,
        selectedSingleMode,
        selectedMultiModes: newMultiModes
      });
    }
  };

  // Start game function (host only)
  const startGame = () => {
    if (!socket || !isHost) return;

    if (multiModeEnabled) {
      // Use maxModes from room data or calculate based on player count
      const maxModes = roomData?.maxModes || (roomData?.players?.length === 2 ? 2 : 3);
      
      const activeGameModes = [];
      if (maxModes >= 1) activeGameModes.push(selectedMultiModes.first);
      if (maxModes >= 2) activeGameModes.push(selectedMultiModes.second);
      if (maxModes >= 3) activeGameModes.push(selectedMultiModes.third);
      
      // Start multi-mode game
      socket.emit('startMultiModeGame', {
        activeGameModes: activeGameModes
      });
    } else {
      // Start single-mode game
      socket.emit('startGame', { gameMode: selectedSingleMode });
    }
  };

  const copyRoomCode = async () => {
    try {
      await navigator.clipboard.writeText(playerData?.roomCode);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      // Handle copy error silently - user will notice if it doesn't work
    }
  };

  return (
    <div className="p-4 py-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <button
            onClick={onLeaveRoom}
            className="btn-secondary flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Leave Game
          </button>
          
          <div className="text-center">
            <h1 className="text-2xl font-bold text-gray-800">Multi-Mode Tambola</h1>
            <p className="text-gray-600">
              {roomData?.gameState === 'lobby' ? 'Waiting in Lobby' : `Status: ${roomData?.gameState}`}
            </p>
          </div>
          
          <div className="flex items-center gap-2 text-gray-600">
            <Users className="w-5 h-5" />
            <span>{roomData?.players?.length || 0} Players</span>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Players List */}
          <div className="card p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-800 flex items-center gap-2">
                <Users className="w-5 h-5" />
                Players ({roomData?.players?.length || 0})
              </h2>
              
              <div className="flex items-center gap-2">
                <button
                  onClick={copyRoomCode}
                  className="flex items-center gap-2 bg-gray-100 hover:bg-gray-200 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
                >
                  {copied ? (
                    <>
                      <Check className="w-4 h-4 text-green-600" />
                      <span className="text-green-600">Copied!</span>
                    </>
                  ) : (
                    <>
                      <Copy className="w-4 h-4" />
                      {playerData?.roomCode}
                    </>
                  )}
                </button>
                
                {isHost && (
                  <button
                    onClick={() => setShowQRCode(true)}
                    className="flex items-center gap-2 bg-primary-100 hover:bg-primary-200 text-primary-700 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
                    title="Show QR Code for easy joining"
                  >
                    <QrCode className="w-4 h-4" />
                    QR
                  </button>
                )}
              </div>
            </div>

            <div className="space-y-3">
              {roomData?.players?.map((player) => (
                <div
                  key={player.id}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div className="flex items-center gap-3">
                    <div className={`w-3 h-3 rounded-full ${
                      player.id === playerData?.playerId 
                        ? 'bg-primary-500' 
                        : 'bg-gray-300'
                    }`}></div>
                    <span className="font-medium text-gray-800">
                      {player.nickname}
                      {player.id === playerData?.playerId && ' (You)'}
                    </span>
                  </div>
                  
                  {player.isHost && (
                    <div className="flex items-center gap-1 bg-warning-100 text-warning-800 px-2 py-1 rounded-full text-xs font-medium">
                      <Crown className="w-3 h-3" />
                      Host
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="mt-4 p-3 bg-blue-50 rounded-lg">
              <p className="text-sm text-blue-700">
                Share the room code <strong>{playerData?.roomCode}</strong> with friends to invite them!
                {isHost && <span className="block mt-1">💡 Tip: Use the QR button above for easier sharing</span>}
              </p>
            </div>

            {/* HOST SUPERPOWERS - Host Controls in Lobby */}
            {isHost && roomData?.players?.length > 1 && (
              <div className="mt-4 p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Crown className="w-4 h-4 text-warning-600" />
                    <span className="text-sm font-medium text-gray-800">Host Controls</span>
                  </div>
                  
                  <div className="relative" ref={playerManagementRef}>
                    <button
                      onClick={() => setShowPlayerManagement(!showPlayerManagement)}
                      className="flex items-center gap-2 px-3 py-1.5 rounded-lg font-medium transition-all bg-gray-100 text-gray-700 hover:bg-gray-200 text-sm"
                      title="Manage players"
                    >
                      <Users className="w-4 h-4" />
                      Manage Players
                    </button>
                    
                    {showPlayerManagement && (
                      <div className="absolute top-full right-0 mt-2 bg-white rounded-lg shadow-lg border border-gray-200 z-50 min-w-48">
                        <div className="p-2">
                          <button
                            onClick={openTransferHostDialog}
                            className="w-full flex items-center gap-2 px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 rounded"
                          >
                            <Crown className="w-4 h-4" />
                            Transfer Host
                          </button>
                          <div className="border-t border-gray-100 my-1"></div>
                          <div className="text-xs text-gray-500 px-3 py-1 font-medium">Kick Players:</div>
                          {roomData?.players?.filter(p => p.id !== playerData?.playerId && p.isConnected).map(player => (
                            <button
                              key={player.id}
                              onClick={() => openKickConfirmation(player)}
                              className="w-full flex items-center gap-2 px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 rounded"
                            >
                              <UserMinus className="w-4 h-4" />
                              {player.nickname}
                            </button>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Game Mode Selection (Host Only) */}
          <div className="card p-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-4">
              {isHost ? 'Game Setup' : 'Game Modes'}
            </h2>
            
            {isHost ? (
              <div className="space-y-4">
                {/* Mode Type Toggle */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700">Game Type:</label>
                  <div className="flex items-center space-x-4">
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        checked={!multiModeEnabled}
                        onChange={() => handleMultiModeToggle(false)}
                        className="text-primary-600 focus:ring-primary-500"
                      />
                      <span className="text-sm">Single Mode</span>
                    </label>
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        checked={multiModeEnabled}
                        onChange={() => handleMultiModeToggle(true)}
                        className="text-primary-600 focus:ring-primary-500"
                      />
                      <span className="text-sm">
                        Multi-Mode ({(roomData?.maxModes || (roomData?.players?.length === 2 ? 2 : 3))} winners)
                      </span>
                    </label>
                  </div>
                </div>

                {/* Single Mode Selection */}
                {!multiModeEnabled && (
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-700">Select Game Mode:</label>
                    <select
                      value={selectedSingleMode}
                      onChange={(e) => handleSingleModeChange(e.target.value)}
                      className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                    >
                      {Object.entries(GAME_MODES).map(([key, mode]) => (
                        <option key={key} value={key}>
                          {mode.icon} {mode.name} - {mode.description}
                        </option>
                      ))}
                    </select>
                  </div>
                )}

                {/* Multi-Mode Selection */}
                {multiModeEnabled && (
                  <div className="space-y-3">
                    {(() => {
                      const maxModes = roomData?.maxModes || (roomData?.players?.length === 2 ? 2 : 3);
                      const totalPlayers = roomData?.players?.length || 0;
                      const positions = maxModes === 2 
                        ? ['first', 'second'] 
                        : ['first', 'second', 'third'];
                      
                      return (
                        <>
                          <label className="text-sm font-medium text-gray-700">
                            Select {maxModes} Game Modes for {totalPlayers} Players:
                          </label>
                          
                          {positions.map((position, index) => (
                            <div key={position} className="space-y-1">
                              <label className="text-xs font-medium text-gray-600">
                                {position === 'first' ? '1st Place' : position === 'second' ? '2nd Place' : '3rd Place'}:
                              </label>
                              <select
                                value={selectedMultiModes[position]}
                                onChange={(e) => handleMultiModeChange(position, e.target.value)}
                                className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm"
                              >
                                {Object.entries(GAME_MODES).map(([key, mode]) => (
                                  <option key={key} value={key}>
                                    {mode.icon} {mode.name}
                                  </option>
                                ))}
                              </select>
                            </div>
                          ))}
                        </>
                      );
                    })()}
                  </div>
                )}

                {/* Start Game Button */}
                <button
                  onClick={startGame}
                  disabled={!roomData?.players || roomData.players.length < 2}
                  className="w-full btn-primary flex items-center justify-center gap-2 mt-6 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Play className="w-4 h-4" />
                  Start Game
                </button>
                
                {roomData?.players && roomData.players.length < 2 && (
                  <p className="text-sm text-red-600 text-center">
                    Need at least 2 players to start the game
                  </p>
                )}
              </div>
            ) : (
              <div className="space-y-4">
                <div className="text-center text-gray-600">
                  <p className="mb-2">🎮 Waiting for host to configure game...</p>
                  <p className="text-sm">
                    Game type will be selected by <strong>{roomData?.players?.find(p => p.isHost)?.nickname}</strong>
                  </p>
                </div>
                
                {/* Show current host selection to players */}
                <div className="border-t pt-4">
                  <h3 className="font-medium text-gray-700 mb-2">Current Selection:</h3>
                  <div className="bg-gray-50 p-3 rounded-lg">
                    {multiModeEnabled ? (
                      <div>
                        <p className="text-sm font-medium text-gray-600 mb-2">Multi-Mode Game:</p>
                        <div className="space-y-1 text-xs">
                          {(() => {
                            const maxModes = roomData?.maxModes || (roomData?.players?.length === 2 ? 2 : 3);
                            const positions = maxModes === 2 
                              ? ['first', 'second'] 
                              : ['first', 'second', 'third'];
                            
                            return positions.map((position, index) => {
                              const rankDisplay = index === 0 ? '🥇 1st' : index === 1 ? '🥈 2nd' : '🥉 3rd';
                              return (
                                <div key={position}>
                                  {rankDisplay}: {GAME_MODES[selectedMultiModes[position]]?.name}
                                </div>
                              );
                            });
                          })()}
                        </div>
                      </div>
                    ) : (
                      <div>
                        <p className="text-sm font-medium text-gray-600 mb-1">Single Mode:</p>
                        <p className="text-sm">{GAME_MODES[selectedSingleMode]?.icon} {GAME_MODES[selectedSingleMode]?.name}</p>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      
      {/* QR Code Modal */}
      {showQRCode && (
        <QRCodeGenerator
          roomCode={playerData?.roomCode}
          onClose={() => setShowQRCode(false)}
        />
      )}

      {/* HOST SUPERPOWERS - Confirmation Dialogs */}
      
      {/* Kick Player Confirmation */}
      {showKickConfirm && selectedPlayerToKick && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
            <h3 className="text-lg font-semibold mb-4 text-red-600">Kick Player</h3>
            <p className="text-gray-700 mb-6">
              Are you sure you want to kick <strong>{selectedPlayerToKick.nickname}</strong> from the lobby?
            </p>
            <div className="flex gap-3">
              <button
                onClick={confirmKickPlayer}
                disabled={hostActionLoading}
                className="flex-1 bg-red-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-red-700 disabled:opacity-50"
              >
                {hostActionLoading ? 'Kicking...' : 'Kick Player'}
              </button>
              <button
                onClick={() => {
                  setShowKickConfirm(false);
                  setSelectedPlayerToKick(null);
                }}
                className="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded-lg font-medium hover:bg-gray-400"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Transfer Host Confirmation */}
      {showTransferHost && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
            <h3 className="text-lg font-semibold mb-4 text-warning-600">Transfer Host</h3>
            <p className="text-gray-700 mb-4">
              Choose a player to transfer host role to:
            </p>
            <div className="space-y-2 mb-6">
              {roomData?.players?.filter(p => p.id !== playerData?.playerId && p.isConnected).map(player => (
                <label key={player.id} className="flex items-center space-x-3">
                  <input
                    type="radio"
                    name="hostTransfer"
                    value={player.id}
                    checked={selectedPlayerForHost === player.id}
                    onChange={(e) => setSelectedPlayerForHost(e.target.value)}
                    className="text-warning-600 focus:ring-warning-500"
                  />
                  <span className="text-gray-700">{player.nickname}</span>
                </label>
              ))}
            </div>
            <div className="flex gap-3">
              <button
                onClick={confirmTransferHost}
                disabled={hostActionLoading || !selectedPlayerForHost}
                className="flex-1 bg-warning-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-warning-700 disabled:opacity-50"
              >
                {hostActionLoading ? 'Transferring...' : 'Transfer Host'}
              </button>
              <button
                onClick={() => {
                  setShowTransferHost(false);
                  setSelectedPlayerForHost(null);
                }}
                className="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded-lg font-medium hover:bg-gray-400"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Lobby;
