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.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="relative flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-[#0a0a1a] via-[#1a1040] to-[#0d1b2a] px-4 bg-pattern">
      <div className="absolute top-1/3 left-1/4 w-56 h-56 bg-purple-500/8 rounded-full blur-3xl animate-blob" />

      <div className="animate-slide-up relative z-10 w-full max-w-md">
        <h1 className="font-display text-2xl sm:text-3xl md:text-4xl font-bold text-gradient text-center mb-6 md:mb-8">
          Присоединиться
        </h1>

        <form onSubmit={handleJoin} className="glass-strong p-6 md:p-8 rounded-2xl w-full 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.5 rounded-xl bg-white/5 text-white border border-white/10 focus:outline-none focus:border-blue-400/50 focus:bg-white/8 uppercase text-center text-xl md:text-2xl tracking-[0.3em] font-display transition-all duration-300 placeholder-gray-500"
              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.5 rounded-xl bg-white/5 text-white border border-white/10 focus:outline-none focus:border-blue-400/50 focus:bg-white/8 transition-all duration-300 placeholder-gray-500"
              placeholder="Введите название" required />
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-500/20 border border-red-500/30 text-red-300 rounded-xl text-sm md:text-base animate-scale-in">
              {error}
            </div>
          )}

          <button type="submit"
            className="w-full btn-glow bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-bold py-3.5 rounded-xl transition-all duration-300 shadow-lg hover:shadow-blue-500/25 hover:scale-[1.02] active:scale-[0.98]">
            Присоединиться
          </button>
          <button type="button" onClick={() => navigate('/')}
            className="w-full mt-3 glass hover:bg-white/10 text-white font-bold py-3.5 rounded-xl transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]">
            ← Назад
          </button>
        </form>
      </div>
    </div>
  )
}

export default JoinGame
