import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import socket from '../socket'

function JoinGame() {
  const [gameCode, setGameCode] = useState('')
  const [teamName, setTeamName] = useState('')
  const [error, setError] = useState('')
  const navigate = useNavigate()

  useEffect(() => {
    // Слушаем события
    const handleGameUpdated = () => {
      // Сохраняем в localStorage перед навигацией
      localStorage.setItem('gameSession', JSON.stringify({
        gameCode: gameCode.toUpperCase(),
        teamName,
        isHost: false
      }))

      navigate(`/game/${gameCode.toUpperCase()}`, { state: { teamName } })
    }

    const handleError = ({ message }) => {
      setError(message)
    }

    socket.on('game-updated', handleGameUpdated)
    socket.on('error', handleError)

    return () => {
      socket.off('game-updated', handleGameUpdated)
      socket.off('error', handleError)
    }
  }, [gameCode, teamName, navigate])

  const handleJoin = (e) => {
    e.preventDefault()
    setError('')
    socket.emit('join-game', { gameCode: gameCode.toUpperCase(), teamName })
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 px-4">
      <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold text-blue-400 mb-6 md:mb-8">
        Присоединиться к игре
      </h1>

      <form onSubmit={handleJoin} className="bg-slate-800 p-6 md:p-8 rounded-xl w-full max-w-md border border-slate-700 shadow-xl">
        <div className="mb-4">
          <label className="block text-gray-300 mb-2 font-medium text-sm md:text-base">Код игры</label>
          <input
            type="text"
            value={gameCode}
            onChange={(e) => setGameCode(e.target.value.toUpperCase())}
            className="w-full p-3 rounded-lg bg-slate-900 text-white border border-slate-600 focus:outline-none focus:border-blue-500 uppercase text-center text-xl md:text-2xl tracking-wider transition-colors"
            placeholder="ABC123"
            maxLength={6}
            required
          />
        </div>

        <div className="mb-6">
          <label className="block text-gray-300 mb-2 font-medium text-sm md:text-base">Название команды</label>
          <input
            type="text"
            value={teamName}
            onChange={(e) => setTeamName(e.target.value)}
            className="w-full p-3 rounded-lg bg-slate-900 text-white border border-slate-600 focus:outline-none focus:border-blue-500 transition-colors"
            required
          />
        </div>

        {error && (
          <div className="mb-4 p-3 bg-red-600/90 text-white rounded-lg text-sm md:text-base">
            {error}
          </div>
        )}

        <button
          type="submit"
          className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-lg transition-all duration-200 shadow-lg hover:shadow-xl"
        >
          Присоединиться
        </button>

        <button
          type="button"
          onClick={() => navigate('/')}
          className="w-full mt-3 bg-slate-700 hover:bg-slate-600 text-white font-bold py-3 rounded-lg transition-all duration-200 shadow-lg"
        >
          Назад
        </button>
      </form>
    </div>
  )
}

export default JoinGame
