"use client";

import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { OptionButton } from "./OptionButton";
import { QuizTimer } from "./QuizTimer";
import { ResultCard } from "./ResultCard";
import { CheckCircle, XCircle, ChevronRight, Lightbulb } from "lucide-react";

interface Option {
  id: string;
  content: string;
  isCorrect: boolean;
  order: number;
}

interface Question {
  id: string;
  content: string;
  image?: string | null;
  explanation?: string | null;
  points: number;
  options: Option[];
}

interface QuizEngineProps {
  quiz: {
    id: string;
    title: string;
    timeLimit: number;
    difficulty: string;
  };
  questions: Question[];
  isGuest?: boolean;
}

type QuizState = "playing" | "feedback" | "result";

interface Answer {
  questionId: string;
  optionId: string | null;
  isCorrect: boolean;
  timeTaken: number;
}

export function QuizEngine({ quiz, questions, isGuest = false }: QuizEngineProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [state, setState] = useState<QuizState>("playing");
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const [answers, setAnswers] = useState<Answer[]>([]);
  const [questionStartTime, setQuestionStartTime] = useState(Date.now());
  const [totalTimeTaken, setTotalTimeTaken] = useState(0);

  const currentQuestion = questions[currentIndex];
  const isLastQuestion = currentIndex === questions.length - 1;

  // Reset timer when question changes
  useEffect(() => {
    setQuestionStartTime(Date.now());
  }, [currentIndex]);

  const handleAnswer = useCallback((optionId: string) => {
    if (state !== "playing" || selectedOption) return;

    const timeTaken = Math.floor((Date.now() - questionStartTime) / 1000);
    const option = currentQuestion.options.find((o) => o.id === optionId);
    const isCorrect = option?.isCorrect ?? false;

    setSelectedOption(optionId);
    setAnswers((prev) => [
      ...prev,
      { questionId: currentQuestion.id, optionId, isCorrect, timeTaken },
    ]);
    setTotalTimeTaken((prev) => prev + timeTaken);
    setState("feedback");
  }, [state, selectedOption, currentQuestion, questionStartTime]);

  const handleTimeout = useCallback(() => {
    if (state !== "playing") return;
    const timeTaken = quiz.timeLimit;
    setAnswers((prev) => [
      ...prev,
      { questionId: currentQuestion.id, optionId: null, isCorrect: false, timeTaken },
    ]);
    setTotalTimeTaken((prev) => prev + timeTaken);
    setState("feedback");
  }, [state, currentQuestion, quiz.timeLimit]);

  const handleNext = useCallback(() => {
    if (isLastQuestion) {
      setState("result");
    } else {
      setCurrentIndex((prev) => prev + 1);
      setSelectedOption(null);
      setState("playing");
    }
  }, [isLastQuestion]);

  const correctAnswer = currentQuestion?.options.find((o) => o.isCorrect);
  const isLastAnswerCorrect = answers[answers.length - 1]?.isCorrect;

  if (state === "result") {
    const score = answers.reduce((sum, a) => {
      const q = questions.find((q) => q.id === a.questionId);
      return a.isCorrect ? sum + (q?.points ?? 10) : sum;
    }, 0);
    const totalPoints = questions.reduce((sum, q) => sum + q.points, 0);
    const percentage = Math.round((score / totalPoints) * 100);

    return (
      <ResultCard
        quiz={quiz}
        score={score}
        totalPoints={totalPoints}
        percentage={percentage}
        timeTaken={totalTimeTaken}
        answers={answers}
        questions={questions}
        isGuest={isGuest}
      />
    );
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-sm border-b border-border">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-between mb-3">
            <span className="text-sm font-medium text-muted-foreground">
              Soal {currentIndex + 1} / {questions.length}
            </span>
            <QuizTimer
              key={currentIndex}
              duration={quiz.timeLimit}
              onTimeout={handleTimeout}
              isRunning={state === "playing"}
            />
            <span className="text-sm font-semibold text-primary">
              {answers.filter((a) => a.isCorrect).length} benar
            </span>
          </div>

          {/* Progress Bar */}
          <div className="h-2 bg-muted rounded-full overflow-hidden">
            <motion.div
              className="h-full gradient-brand rounded-full"
              initial={{ width: `${(currentIndex / questions.length) * 100}%` }}
              animate={{ width: `${((currentIndex + (state === "feedback" ? 1 : 0)) / questions.length) * 100}%` }}
              transition={{ duration: 0.5 }}
            />
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 container mx-auto px-4 py-8 max-w-2xl">
        <AnimatePresence mode="wait">
          <motion.div
            key={currentIndex}
            initial={{ opacity: 0, x: 50 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -50 }}
            transition={{ duration: 0.3, ease: "easeInOut" }}
          >
            {/* Question */}
            <div className="mb-8">
              <div className="bg-card border border-border rounded-2xl p-6 mb-6">
                <p className="text-xl font-semibold leading-relaxed">
                  {currentQuestion.content}
                </p>
              </div>

              {/* Options */}
              <div className="space-y-3">
                {currentQuestion.options
                  .sort((a, b) => a.order - b.order)
                  .map((option, i) => (
                    <OptionButton
                      key={option.id}
                      option={option}
                      index={i}
                      selectedOptionId={selectedOption}
                      state={state}
                      onSelect={handleAnswer}
                    />
                  ))}
              </div>
            </div>

            {/* Feedback */}
            <AnimatePresence>
              {state === "feedback" && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="space-y-4"
                >
                  {/* Result indicator */}
                  <div
                    className={`flex items-center gap-3 p-4 rounded-2xl ${
                      isLastAnswerCorrect
                        ? "bg-emerald-500/10 border border-emerald-500/30"
                        : "bg-rose-500/10 border border-rose-500/30"
                    }`}
                  >
                    {isLastAnswerCorrect ? (
                      <CheckCircle className="w-6 h-6 text-emerald-500 flex-shrink-0" />
                    ) : (
                      <XCircle className="w-6 h-6 text-rose-500 flex-shrink-0" />
                    )}
                    <div>
                      <p className={`font-bold ${isLastAnswerCorrect ? "text-emerald-500" : "text-rose-500"}`}>
                        {isLastAnswerCorrect ? "Benar! 🎉" : "Salah!"}
                      </p>
                      {!isLastAnswerCorrect && (
                        <p className="text-sm text-muted-foreground">
                          Jawaban benar: <strong>{correctAnswer?.content}</strong>
                        </p>
                      )}
                    </div>
                    {isLastAnswerCorrect && (
                      <span className="ml-auto font-bold text-emerald-500">
                        +{currentQuestion.points} poin
                      </span>
                    )}
                  </div>

                  {/* Explanation */}
                  {currentQuestion.explanation && (
                    <div className="flex gap-3 p-4 bg-amber-500/10 border border-amber-500/20 rounded-2xl">
                      <Lightbulb className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" />
                      <p className="text-sm leading-relaxed">{currentQuestion.explanation}</p>
                    </div>
                  )}

                  {/* Next Button */}
                  <motion.button
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={handleNext}
                    className="w-full flex items-center justify-center gap-2 py-4 gradient-brand text-white font-bold text-lg rounded-2xl shadow-lg shadow-indigo-500/25"
                  >
                    {isLastQuestion ? "Lihat Hasil" : "Soal Berikutnya"}
                    <ChevronRight className="w-5 h-5" />
                  </motion.button>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        </AnimatePresence>
      </div>
    </div>
  );
}
