import { useState, useEffect } from 'react'
import { useParams, useLocation, useNavigate } from 'react-router-dom'
import socket from '../socket'
import GameBoard from '../components/GameBoard'
import QuestionModal from '../components/QuestionModal'
import TeamScores from '../components/TeamScores'

function Game() {
  const { gameCode } = useParams()
  const location = useLocation()
  const navigate = useNavigate()

  const getSessionData = () => {
    if (location.state) return location.state
    const savedSession = localStorage.getItem('gameSession')
    if (savedSession) {
      const session = JSON.parse(savedSession)
      if (session.gameCode === gameCode) return session
    }
    return {}
  }

  const { teamName, isHost, hostName } = getSessionData()

  const [game, setGame] = useState(null)
  const [questions, setQuestions] = useState([])
  const [currentQuestion, setCurrentQuestion] = useState(null)
  const [timer, setTimer] = useState(null)
  const [myTeam, setMyTeam] = useState(null)
  const [answerMedia, setAnswerMedia] = useState(null)
  const [shouldFinishAfterMedia, setShouldFinishAfterMedia] = useState(false)

  useEffect(() => {
    if (!teamName && !isHost) {
      console.warn('No team name or host status, redirecting to home')
      navigate('/')
    }
  }, [teamName, isHost, navigate])

  useEffect(() => {
    if (isHost) {
      socket.emit('host-join-game', { gameCode })
    } else if (teamName) {
      socket.emit('join-game', { gameCode, teamName })
    }
  }, [isHost, teamName, gameCode])

  useEffect(() => {
    socket.on('game-updated', (updatedGame) => {
      setGame(updatedGame)
      if (!isHost && teamName) {
        const team = updatedGame.teams.find(t => t.name === teamName)
        setMyTeam(team)
      }
      if (updatedGame.selectedCategories) setQuestions(updatedGame.selectedCategories)
    })

    socket.on('game-started', (game) => {
      setGame(game)
      if (!isHost && teamName) {
        const team = game.teams.find(t => t.name === teamName)
        setMyTeam(team)
      }
      if (game.selectedCategories) setQuestions(game.selectedCategories)
    })

    socket.on('host-game-loaded', (loadedGame) => {
      setGame(loadedGame)
      if (loadedGame.selectedCategories) setQuestions(loadedGame.selectedCategories)
    })

    socket.on('question-selected', ({ category, points, questionIndex, timer }) => {
      const categoryData = questions?.find(cat => cat.name === category)
      const questionData = questionIndex !== undefined
        ? categoryData?.questions[questionIndex]
        : categoryData?.questions.find(q => q.points === points)
      console.log(`📥 Question selected: category="${category}", points=${points}, questionIndex=${questionIndex}`, questionData);
      setCurrentQuestion({ ...questionData, category, points })
      setTimer(timer)
    })

    socket.on('timer-update', ({ timer }) => { setTimer(timer) })

    socket.on('time-up', ({ answerMedia, shouldFinish }) => {
      if (answerMedia) {
        setAnswerMedia(answerMedia)
        if (shouldFinish) setShouldFinishAfterMedia(true)
      }
      setCurrentQuestion(null)
      setTimer(null)
    })

    socket.on('team-buzzing', ({ teamId, teamName }) => {
      console.log(`${teamName} buzzing!`)
    })

    socket.on('answer-result', ({ teamId, isCorrect, questionClosed, answerMedia, shouldFinish }) => {
      console.log('Answer result:', { teamId, isCorrect, questionClosed, answerMedia, shouldFinish })
      if (questionClosed) {
        if (answerMedia) {
          setAnswerMedia(answerMedia)
          if (shouldFinish) setShouldFinishAfterMedia(true)
        }
        setTimeout(() => {
          setCurrentQuestion(null)
          setTimer(null)
        }, 2000)
      } else {
        console.log('Incorrect answer, waiting for other teams')
      }
    })

    socket.on('round-changed', ({ round }) => {
      console.log(`Round ${round} started`)
      setCurrentQuestion(null)
      setTimer(null)
      setAnswerMedia(null)
    })

    socket.on('game-finished', (finishedGame) => { setGame(finishedGame) })

    return () => {
      socket.off('game-updated')
      socket.off('game-started')
      socket.off('host-game-loaded')
      socket.off('question-selected')
      socket.off('timer-update')
      socket.off('time-up')
      socket.off('team-buzzing')
      socket.off('answer-result')
      socket.off('round-changed')
      socket.off('game-finished')
    }
  }, [teamName, questions, isHost])

  const handleStartGame = () => { socket.emit('start-game', { gameCode }) }
  const handleSelectQuestion = (category, points) => {
    if (isHost) socket.emit('select-question', { gameCode, category, points })
  }
  const handleBuzzIn = () => {
    if (myTeam) socket.emit('buzz-in', { gameCode, teamId: myTeam.id })
  }
  const handleSubmitAnswer = (isCorrect) => {
    console.log('handleSubmitAnswer called', { isHost, answeringTeam: game.answeringTeam, isCorrect })
    if (isHost && game.answeringTeam) {
      console.log('Sending submit-answer', { gameCode, teamId: game.answeringTeam, isCorrect })
      socket.emit('submit-answer', { gameCode, teamId: game.answeringTeam, isCorrect })
    } else {
      console.log('Not sending: isHost=', isHost, 'answeringTeam=', game.answeringTeam)
    }
  }
  const handleCloseQuestion = () => {
    if (isHost) socket.emit('close-question', { gameCode })
  }
  const handleFinishGame = () => {
    if (isHost) socket.emit('finish-game', { gameCode })
  }
  const handleCloseAnswerMedia = () => {
    setAnswerMedia(null)
    if (shouldFinishAfterMedia && isHost) {
      setShouldFinishAfterMedia(false)
      socket.emit('finish-game', { gameCode })
    }
  }

  if (!game) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-[#0a0a1a] via-[#1a1040] to-[#0d1b2a] px-4">
        <div className="text-center animate-pulse-slow">
          <div className="text-6xl mb-4">🧠</div>
          <h2 className="font-display text-2xl md:text-3xl font-bold text-gradient mb-4">Загрузка...</h2>
        </div>
      </div>
    )
  }

  // Results screen
  if (game.status === 'finished') {
    const sortedTeams = [...game.teams].sort((a, b) => b.score - a.score)
    const winner = sortedTeams[0]
    const medals = ['🥇', '🥈', '🥉']

    return (
      <div className="min-h-screen p-4 md:p-8 bg-gradient-to-br from-[#0a0a1a] via-[#1a1040] to-[#0d1b2a] bg-pattern">
        <div className="max-w-4xl mx-auto">
          <div className="text-center mb-8 md:mb-12 animate-slide-up">
            <h1 className="font-display text-3xl md:text-6xl font-black text-gradient-gold mb-6">ИГРА ЗАВЕРШЕНА!</h1>
            <div className="glass-strong p-6 md:p-10 rounded-2xl mb-6 md:mb-8 glow-gold">
              <p className="text-2xl md:text-4xl font-bold text-white mb-3">🏆 ПОБЕДИТЕЛЬ 🏆</p>
              <p className="font-display text-3xl md:text-5xl font-black text-gradient-gold">{winner.name}</p>
              <p className="font-display text-xl md:text-3xl font-bold text-amber-300 mt-3">{winner.score} баллов</p>
            </div>
          </div>

          <div className="glass-strong p-4 md:p-8 rounded-2xl mb-6 md:mb-8">
            <h2 className="font-display text-xl md:text-2xl font-bold text-white mb-4 md:mb-6 text-center">Итоговая таблица</h2>
            <div className="space-y-2 md:space-y-3">
              {sortedTeams.map((team, index) => (
                <div key={team.id}
                  className={`flex justify-between items-center p-4 md:p-5 rounded-xl transition-all duration-300 animate-slide-up border ${
                    index === 0 ? 'bg-gradient-to-r from-amber-600/30 to-yellow-600/30 border-amber-400/30 glow-gold'
                    : index === 1 ? 'bg-gradient-to-r from-gray-400/20 to-gray-500/20 border-gray-400/20'
                    : index === 2 ? 'bg-gradient-to-r from-orange-600/20 to-orange-700/20 border-orange-400/20'
                    : 'glass'
                  }`}
                  style={{ animationDelay: `${index * 0.1}s` }}
                >
                  <div className="flex items-center gap-2 md:gap-4">
                    <span className="text-2xl md:text-4xl">{medals[index] || `#${index + 1}`}</span>
                    <span className="text-base md:text-xl font-bold text-white">{team.name}</span>
                  </div>
                  <span className="font-display text-xl md:text-2xl font-bold text-gradient-gold">{team.score}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="text-center">
            <button onClick={() => navigate('/')}
              className="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 md:py-4 px-8 md:px-12 rounded-2xl text-base md:text-xl transition-all duration-300 shadow-lg hover:shadow-blue-500/25 hover:scale-[1.02] active:scale-[0.98]">
              🏠 На главную
            </button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen p-3 md:p-6 bg-gradient-to-br from-[#0a0a1a] via-[#1a1040] to-[#0d1b2a] bg-pattern">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-4 md:mb-6">
          <h1 className="font-display text-2xl md:text-4xl font-black text-gradient mb-2 md:mb-3">СВОЯ ИГРА</h1>
          <div className="glass inline-flex items-center gap-3 md:gap-5 px-4 md:px-6 py-2 md:py-3 rounded-xl">
            <span className="text-xs md:text-base text-gray-400">
              Код: <span className="font-display text-blue-300 font-bold tracking-wider">{gameCode}</span>
            </span>
            {isHost && (
              <span className="text-xs md:text-sm text-gray-500">• {hostName}</span>
            )}
            <span className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-3 md:px-4 py-0.5 md:py-1 rounded-lg font-bold text-xs md:text-sm font-display">
              Раунд {game.currentRound}
            </span>
          </div>
        </div>

        {/* Team scores */}
        <TeamScores teams={game.teams} myTeamId={myTeam?.id} />

        {/* Waiting state */}
        {game.status === 'waiting' && isHost && (
          <div className="text-center my-6 md:my-8 animate-slide-up">
            <div className="glass-strong p-6 md:p-8 rounded-2xl inline-block">
              <p className="text-white text-base md:text-lg mb-4">
                Ожидание команд... <span className="text-blue-300 font-bold">({game.teams.length})</span>
              </p>
              {game.teams.length > 0 && (
                <button onClick={handleStartGame}
                  className="btn-glow bg-gradient-to-r from-emerald-600 to-green-600 hover:from-emerald-500 hover:to-green-500 text-white font-bold py-3 md:py-4 px-8 md:px-10 rounded-xl text-lg md:text-xl transition-all duration-300 shadow-lg shadow-emerald-500/20 hover:scale-[1.03] active:scale-95 border border-emerald-400/30">
                  ▶️ Начать игру
                </button>
              )}
              {game.teams.length === 0 && (
                <p className="text-gray-500 text-sm md:text-base mt-2">Отправьте код игры командам</p>
              )}
            </div>
          </div>
        )}

        {game.status === 'waiting' && !isHost && (
          <div className="text-center my-6 md:my-8">
            <div className="glass p-6 rounded-2xl inline-block animate-pulse-slow">
              <p className="text-white text-base md:text-lg">⏳ Ожидание начала игры...</p>
            </div>
          </div>
        )}

        {/* Game board */}
        {game.status === 'playing' && (
          <GameBoard
            questions={questions}
            usedQuestions={game.usedQuestions}
            onSelectQuestion={handleSelectQuestion}
            currentRound={game.currentRound}
            isHost={isHost}
          />
        )}

        {/* Question modal */}
        {currentQuestion && (
          <QuestionModal
            question={currentQuestion}
            timer={timer}
            onSubmitAnswer={handleSubmitAnswer}
            answeringTeamName={game.teams.find(t => t.id === game.answeringTeam)?.name}
            isHost={isHost}
            onBuzzIn={handleBuzzIn}
            canBuzzIn={!isHost && !game.answeringTeam && myTeam && !(game.answeredTeams || []).includes(myTeam.id)}
            onCloseQuestion={handleCloseQuestion}
            gameCode={gameCode}
            socket={socket}
          />
        )}

        {/* Answer media modal */}
        {answerMedia && (
          <div className="fixed inset-0 bg-black/90 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-scale-in">
            <div className="glass-strong p-6 md:p-10 rounded-2xl max-w-4xl w-full shadow-2xl glow-blue">
              <h2 className="font-display text-2xl md:text-4xl font-bold text-gradient text-center mb-6 md:mb-8">
                Правильный ответ
              </h2>
              <div className="glass p-4 md:p-6 rounded-xl mb-6 md:mb-8">
                <audio controls autoPlay
                  src={`${window.location.protocol}//${window.location.host}${answerMedia}`}
                  className="w-full" onEnded={handleCloseAnswerMedia}>
                  Ваш браузер не поддерживает аудио элемент.
                </audio>
              </div>
              <div className="text-center">
                <button onClick={handleCloseAnswerMedia}
                  className="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 md:py-4 px-8 md:px-12 rounded-xl text-lg md:text-xl transition-all duration-300 shadow-lg hover:scale-[1.02] active:scale-[0.98]">
                  Закрыть
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Next round button */}
        {isHost && game.usedQuestions.length >= 25 && game.status === 'playing' && (
          <div className="text-center mt-4 md:mt-6">
            <button onClick={() => socket.emit('next-round', { gameCode })}
              className="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 md:py-4 px-6 md:px-8 rounded-xl text-base md:text-lg transition-all duration-300 shadow-lg hover:scale-[1.02] active:scale-[0.98]">
              ⏭️ Следующий раунд
            </button>
          </div>
        )}

        {/* Finish game button */}
        {isHost && game.status === 'playing' && (
          <div className="text-center mt-4 md:mt-6">
            <button onClick={handleFinishGame}
              className="glass hover:bg-red-500/20 text-red-300 hover:text-red-200 font-bold py-2 md:py-3 px-6 md:px-8 rounded-xl text-sm md:text-base transition-all duration-300 border-red-500/20 hover:border-red-400/30">
              🏁 Завершить игру
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

export default Game
