import { useState } from 'react'
import Question from './Question'
import Players from './Players'
import PlayersModal from './PlayersModal'
import Score from './Score'
import { questions } from '../data/questions'
import './Game.css'

const Game = () => {
  const [players, setPlayers] = useState([])
  const [currentPlayerId, setCurrentPlayerId] = useState(null)
  const [playerScores, setPlayerScores] = useState({})
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
  const [gameOver, setGameOver] = useState(false)
  const [revealedAnswers, setRevealedAnswers] = useState([])
  const [isPlayersModalOpen, setIsPlayersModalOpen] = useState(false)

  const currentQuestion = questions[currentQuestionIndex]
  const isLastQuestion = currentQuestionIndex === questions.length - 1

  const handleAddPlayer = (name) => {
    const newPlayer = {
      id: Date.now(),
      name: name,
    }
    const updatedPlayers = [...players, newPlayer]
    setPlayers(updatedPlayers)
    
    // Если это первый участник, делаем его текущим
    if (updatedPlayers.length === 1) {
      setCurrentPlayerId(newPlayer.id)
      setPlayerScores({ [newPlayer.id]: 0 })
    } else {
      setPlayerScores({ ...playerScores, [newPlayer.id]: 0 })
    }
  }

  const handleSelectPlayer = (playerId) => {
    setCurrentPlayerId(playerId)
  }

  const handleRemovePlayer = (playerId) => {
    const updatedPlayers = players.filter(p => p.id !== playerId)
    setPlayers(updatedPlayers)
    
    const updatedScores = { ...playerScores }
    delete updatedScores[playerId]
    setPlayerScores(updatedScores)

    // Если удалили текущего участника, выбираем другого
    if (currentPlayerId === playerId) {
      if (updatedPlayers.length > 0) {
        setCurrentPlayerId(updatedPlayers[0].id)
      } else {
        setCurrentPlayerId(null)
      }
    }
  }

  const getNextPlayerId = () => {
    if (players.length === 0) return null
    if (players.length === 1) return currentPlayerId
    
    const currentIndex = players.findIndex(p => p.id === currentPlayerId)
    const nextIndex = (currentIndex + 1) % players.length
    return players[nextIndex].id
  }

  const handleAnswerClick = (answerIndex, points) => {
    if (revealedAnswers.includes(answerIndex)) return
    if (!currentPlayerId) return

    const isLastAnswer = revealedAnswers.length === currentQuestion.answers.length - 1
    
    setRevealedAnswers([...revealedAnswers, answerIndex])
    
    // Добавляем очки текущему участнику
    setPlayerScores({
      ...playerScores,
      [currentPlayerId]: (playerScores[currentPlayerId] || 0) + points,
    })

    // Переходим к следующему участнику только если это не последний ответ
    if (!isLastAnswer) {
      const nextPlayerId = getNextPlayerId()
      if (nextPlayerId) {
        setTimeout(() => {
          setCurrentPlayerId(nextPlayerId)
        }, 500)
      }
    } else {
      // Если это последний ответ, переходим к следующему участнику перед следующим вопросом
      setTimeout(() => {
        const nextPlayerId = getNextPlayerId()
        if (nextPlayerId) {
          setCurrentPlayerId(nextPlayerId)
        }
        
        if (isLastQuestion) {
          setGameOver(true)
        } else {
          setTimeout(() => {
            nextQuestion()
          }, 500)
        }
      }, 2000)
    }
  }

  const nextQuestion = () => {
    setCurrentQuestionIndex(currentQuestionIndex + 1)
    setRevealedAnswers([])
  }

  const restartGame = () => {
    setCurrentQuestionIndex(0)
    setGameOver(false)
    setRevealedAnswers([])
    const initialScores = {}
    players.forEach(player => {
      initialScores[player.id] = 0
    })
    setPlayerScores(initialScores)
    if (players.length > 0) {
      setCurrentPlayerId(players[0].id)
    }
  }

  if (gameOver) {
    // Находим победителя(ей)
    const scores = Object.values(playerScores)
    const maxScore = scores.length > 0 ? Math.max(...scores) : 0
    const winners = players.filter(p => playerScores[p.id] === maxScore)
    
    return (
      <div className="game-over">
        <div className="game-over-content">
          <h2 className="game-over-title">🎉 Игра окончена! 🎉</h2>
          <div className="final-scores">
            <h3 className="final-scores-title">Итоговые результаты:</h3>
            {players
              .sort((a, b) => (playerScores[b.id] || 0) - (playerScores[a.id] || 0))
              .map((player) => (
                <div
                  key={player.id}
                  className={`final-score-item ${
                    winners.includes(player) ? 'final-score-winner' : ''
                  }`}
                >
                  <span className="final-score-name">{player.name}</span>
                  <span className="final-score-value">
                    {playerScores[player.id] || 0} очков
                  </span>
                </div>
              ))}
          </div>
          <button className="restart-button" onClick={restartGame}>
            Играть снова
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="game">
      <PlayersModal
        isOpen={isPlayersModalOpen}
        onClose={() => setIsPlayersModalOpen(false)}
        players={players}
        onAddPlayer={handleAddPlayer}
        onRemovePlayer={handleRemovePlayer}
      />

      <div className="game-header">
        <button
          className="manage-players-button"
          onClick={() => setIsPlayersModalOpen(true)}
        >
          {players.length === 0 ? 'Добавить участников' : 'Управление участниками'}
        </button>
        
        {players.length > 0 && (
          <Players
            players={players}
            currentPlayerId={currentPlayerId}
            playerScores={playerScores}
            onSelectPlayer={handleSelectPlayer}
          />
        )}
      </div>
      
      {players.length > 0 && currentPlayerId ? (
        <>
          <Score
            score={playerScores[currentPlayerId] || 0}
            questionNumber={currentQuestionIndex + 1}
            totalQuestions={questions.length}
          />
          <Question
            question={currentQuestion}
            questionNumber={currentQuestionIndex + 1}
            onAnswerClick={handleAnswerClick}
            revealedAnswers={revealedAnswers}
          />
        </>
      ) : (
        <div className="no-players-message">
          <p>Добавьте участников, чтобы начать игру</p>
        </div>
      )}
    </div>
  )
}

export default Game

