/**
 * Trivia Game - LOTR themed trivia questions
 */

import React, { useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { Button } from '../ui/Button';
import { Card } from '../ui/Card';

interface TriviaGameProps {
  onSuccess: () => void;
  onFail: () => void;
}

interface TriviaQuestion {
  question: string;
  options: string[];
  correct: number;
}

export const TRIVIA_SESSION_SIZE = 4;
export const TRIVIA_REQUIRED_CORRECT = 3;

export const TRIVIA_QUESTION_POOL: TriviaQuestion[] = [
  {
    question: 'What is the name of Frodo\'s best friend?',
    options: ['Gandalf', 'Samwise', 'Boromir', 'Legolas'],
    correct: 1,
  },
  {
    question: 'In which Shire town does Frodo live?',
    options: ['Bree', 'Hobbiton', 'Rivendell', 'Lothlórien'],
    correct: 1,
  },
  {
    question: 'What is the Elvish name for Mithril?',
    options: ['Adamant', 'Moria', 'Silmaril', 'Mithril is only known in Dwarvish'],
    correct: 3,
  },
  {
    question: 'Who forged the One Ring?',
    options: ['Gandalf', 'Elrond', 'Sauron', 'Bilbo Baggins'],
    correct: 2,
  },
  {
    question: 'What is the name of Gandalf\'s horse?',
    options: ['Asfaloth', 'Shadowfax', 'Arod', 'Firefoot'],
    correct: 1,
  },
  {
    question: 'How many members were in the Fellowship?',
    options: ['7', '8', '9', '10'],
    correct: 2,
  },
  {
    question: 'What is the capital of Rohan?',
    options: ['Gondor', 'Edoras', 'Minas Tirith', 'Aragorn'],
    correct: 1,
  },
  {
    question: 'What does "Frodo" mean in Sindarin?',
    options: ['Friend', 'Ring-bearer', 'Wisdom-Dweller', 'Hobbit'],
    correct: 2,
  },
  {
    question: 'Who carries the shards of Narsil to Rivendell?',
    options: ['Arwen', 'Aragorn', 'Boromir', 'Elrond'],
    correct: 1,
  },
  {
    question: 'What creature bites Frodo in Shelob\'s Lair?',
    options: ['Warg', 'Balrog', 'Shelob', 'Watcher in the Water'],
    correct: 2,
  },
  {
    question: 'Which city is known as the White City?',
    options: ['Edoras', 'Minas Tirith', 'Bree', 'Osgiliath'],
    correct: 1,
  },
  {
    question: 'Who says, "You shall not pass!"?',
    options: ['Saruman', 'Elrond', 'Gandalf', 'Theoden'],
    correct: 2,
  },
  {
    question: 'What race is Gimli?',
    options: ['Elf', 'Human', 'Wizard', 'Dwarf'],
    correct: 3,
  },
  {
    question: 'Where is the Council of Elrond held?',
    options: ['Rivendell', 'Helm\'s Deep', 'Minas Tirith', 'The Shire'],
    correct: 0,
  },
  {
    question: 'Who is the father of Legolas in the films?',
    options: ['Thranduil', 'Celeborn', 'Elrond', 'Haldir'],
    correct: 0,
  },
  {
    question: 'Which king of Rohan is freed from Saruman\'s influence?',
    options: ['Eomer', 'Theoden', 'Denethor', 'Bard'],
    correct: 1,
  },
  {
    question: 'What food do the elves give the Fellowship for the journey?',
    options: ['Lembas', 'Mead', 'Mushrooms', 'Salt pork'],
    correct: 0,
  },
  {
    question: 'What is the name of Aragorn\'s sword after it is reforged?',
    options: ['Glamdring', 'Orcrist', 'Andúril', 'Sting'],
    correct: 2,
  },
  {
    question: 'Who tries to take the Ring from Frodo at Amon Hen?',
    options: ['Boromir', 'Sam', 'Merry', 'Pippin'],
    correct: 0,
  },
  {
    question: 'What river do the Fellowship travel down in boats?',
    options: ['Anduin', 'Brandywine', 'Silverlode', 'Isen'],
    correct: 0,
  },
  {
    question: 'Which ent marches on Isengard?',
    options: ['Quickbeam', 'Treebeard', 'Beechbone', 'Skinbark'],
    correct: 1,
  },
  {
    question: 'What title is given to Sauron?',
    options: ['The White Rider', 'The Dark Lord', 'The Grey Pilgrim', 'The Steward'],
    correct: 1,
  },
  {
    question: 'Who guards the secret stair to Mordor?',
    options: ['Faramir', 'Gollum', 'Denethor', 'Eowyn'],
    correct: 1,
  },
  {
    question: 'What is Bilbo\'s sword called?',
    options: ['Sting', 'Gurthang', 'Narsil', 'Herugrim'],
    correct: 0,
  },
  {
    question: 'Who is the Steward of Gondor during the War of the Ring?',
    options: ['Theoden', 'Denethor', 'Faramir', 'Imrahil'],
    correct: 1,
  },
  {
    question: 'What mountain must the Ring be destroyed in?',
    options: ['Mindolluin', 'Mount Doom', 'Caradhras', 'Erebor'],
    correct: 1,
  },
  {
    question: 'Who helps Frodo and Sam enter Mordor in disguise?',
    options: ['Aragorn', 'Gollum', 'Legolas', 'Galadriel'],
    correct: 1,
  },
  {
    question: 'Which member of the Fellowship is an elf?',
    options: ['Boromir', 'Legolas', 'Merry', 'Gimli'],
    correct: 1,
  },
  {
    question: 'Where do Merry and Pippin meet Treebeard?',
    options: ['Fangorn Forest', 'Mirkwood', 'Lothlórien', 'Bree'],
    correct: 0,
  },
  {
    question: 'Who kills the Witch-king of Angmar?',
    options: ['Aragorn', 'Eowyn', 'Gandalf', 'Legolas'],
    correct: 1,
  },
];

const buildTriviaSession = () => {
  const remaining = [...TRIVIA_QUESTION_POOL];
  const selected: TriviaQuestion[] = [];

  while (selected.length < TRIVIA_SESSION_SIZE && remaining.length > 0) {
    const index = Math.floor(Math.random() * remaining.length);
    const [question] = remaining.splice(index, 1);
    selected.push(question);
  }

  return selected;
};

export const TriviaGame: React.FC<TriviaGameProps> = ({ onSuccess, onFail }) => {
  const sessionQuestions = useMemo(() => buildTriviaSession(), []);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [answered, setAnswered] = useState(false);
  const [lastAnswerCorrect, setLastAnswerCorrect] = useState<boolean | null>(null);
  const [correctAnswers, setCorrectAnswers] = useState(0);
  const [isResolvingResult, setIsResolvingResult] = useState(false);

  const currentQuestion = sessionQuestions[currentQuestionIndex];
  const isLastQuestion = currentQuestionIndex === sessionQuestions.length - 1;

  const handleAnswer = (answerIndex: number) => {
    if (answered || isResolvingResult) {
      return;
    }

    const isCorrect = answerIndex === currentQuestion.correct;
    setSelectedAnswer(answerIndex);
    setAnswered(true);
    setLastAnswerCorrect(isCorrect);

    if (isCorrect) {
      setCorrectAnswers((prev) => prev + 1);
    }
  };

  const handleNext = () => {
    if (!answered || isResolvingResult) {
      return;
    }

    if (!isLastQuestion) {
      setCurrentQuestionIndex((prev) => prev + 1);
      setSelectedAnswer(null);
      setAnswered(false);
      setLastAnswerCorrect(null);
      return;
    }

    setIsResolvingResult(true);
    const finalScore = correctAnswers;

    window.setTimeout(() => {
      if (finalScore >= TRIVIA_REQUIRED_CORRECT) {
        onSuccess();
      } else {
        onFail();
      }
    }, 900);
  };

  return (
    <div className="space-y-4">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center"
      >
        <h3 className="text-xl font-epic text-gold-dark mb-2">🧙 Gandalf&apos;s Trivia Challenge</h3>
        <div className="flex items-center justify-center gap-4 text-sm text-text-secondary flex-wrap">
          <p>Question {currentQuestionIndex + 1} of {sessionQuestions.length}</p>
          <p>Score: {correctAnswers}/{TRIVIA_REQUIRED_CORRECT} needed</p>
          <p>Pool: {TRIVIA_QUESTION_POOL.length} questions</p>
        </div>
      </motion.div>

      <motion.div
        key={currentQuestionIndex}
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
        className="space-y-4"
      >
        <Card variant="dark" className="text-center p-4">
          <p className="text-base sm:text-lg font-semibold text-parchment-light leading-relaxed">
            {currentQuestion.question}
          </p>
        </Card>

        <div className="grid grid-cols-1 gap-3">
          {currentQuestion.options.map((option, index) => {
            const isSelected = selectedAnswer === index;
            const selectedStateClass =
              isSelected && lastAnswerCorrect === true
                ? 'bg-green-600 text-white scale-[1.02]'
                : isSelected && lastAnswerCorrect === false
                ? 'bg-red-600 text-white scale-[1.02]'
                : 'bg-forest hover:bg-forest-light text-parchment-light';

            return (
              <motion.button
                key={`${currentQuestion.question}-${index}`}
                type="button"
                onClick={() => handleAnswer(index)}
                disabled={answered || isResolvingResult}
                whileHover={!answered ? { scale: 1.01 } : {}}
                whileTap={!answered ? { scale: 0.99 } : {}}
                className={`w-full min-h-[52px] rounded-lg p-3 text-left font-medium transition-all duration-200 ${selectedStateClass}`}
              >
                {option}
              </motion.button>
            );
          })}
        </div>

        <div className="space-y-3 pt-2">
          <div className="min-h-[24px] text-center font-semibold">
            {answered && lastAnswerCorrect === true && <span className="text-green-400">✓ Correct!</span>}
            {answered && lastAnswerCorrect === false && <span className="text-red-400">✗ Incorrect.</span>}
            {isResolvingResult && (
              <span className={correctAnswers >= TRIVIA_REQUIRED_CORRECT ? 'text-green-400' : 'text-red-400'}>
                {correctAnswers >= TRIVIA_REQUIRED_CORRECT
                  ? 'Challenge cleared. Claim your reward next.'
                  : 'Challenge failed. Resetting for another try.'}
              </span>
            )}
          </div>

          <Button
            onClick={handleNext}
            variant="epic"
            className="w-full"
            disabled={!answered || isResolvingResult}
          >
            {isLastQuestion ? 'See Result' : 'Next Question'}
          </Button>
        </div>
      </motion.div>
    </div>
  );
};

TriviaGame.displayName = 'TriviaGame';
