import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { QUESTIONS, PER_QUESTION, type Question } from "../questions";
import type { QuizAnswer } from "../types";
import { ArrowLeft, ArrowRight, CheckCircle2 } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

function evaluate(q: Question, raw: string): { correct: string; isCorrect: boolean } {
  if (q.type === "mcq") {
    const correct = q.options[q.correctIndex];
    return { correct, isCorrect: raw === correct };
  }
  const norm = raw.trim().toLowerCase().replace(/\s+/g, " ");
  return {
    correct: q.accepted[0],
    isCorrect: q.accepted.some((a) => norm === a.toLowerCase()),
  };
}

export function Quiz({
  onBack,
  onComplete,
}: {
  onBack: () => void;
  onComplete: (answers: QuizAnswer[], score: number) => void;
}) {
  const [idx, setIdx] = useState(0);
  const [responses, setResponses] = useState<string[]>(Array(QUESTIONS.length).fill(""));
  const q = QUESTIONS[idx];
  const value = responses[idx];
  const canNext = value && value.trim().length > 0;

  const next = () => {
    if (idx === QUESTIONS.length - 1) {
      const answers: QuizAnswer[] = QUESTIONS.map((qq, i) => {
        const { correct, isCorrect } = evaluate(qq, responses[i]);
        return { question: qq.q, answer: responses[i], correct, isCorrect };
      });
      const score = Math.round(answers.filter((a) => a.isCorrect).length * PER_QUESTION);
      onComplete(answers, score);
    } else {
      setIdx(idx + 1);
    }
  };

  const prev = () => (idx === 0 ? onBack() : setIdx(idx - 1));

  return (
    <div className="space-y-6">
      <div>
        <div className="flex items-center justify-between text-xs text-muted-foreground mb-2">
          <span>Question {idx + 1} of {QUESTIONS.length}</span>
          <span className="uppercase tracking-wider">{q.type === "mcq" ? "Multiple Choice" : "Fill in the Blank"}</span>
        </div>
        <Progress value={((idx + 1) / QUESTIONS.length) * 100} className="h-1 bg-white/5" />
      </div>

      <AnimatePresence mode="wait">
        <motion.div
          key={idx}
          initial={{ opacity: 0, x: 30 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -30 }}
          transition={{ duration: 0.25 }}
          className="space-y-4"
        >
          <h3 className="text-xl md:text-2xl font-semibold leading-snug">{q.q}</h3>

          {q.type === "mcq" ? (
            <div className="space-y-2.5">
              {q.options.map((opt) => {
                const selected = value === opt;
                return (
                  <button
                    key={opt}
                    onClick={() => {
                      const c = [...responses];
                      c[idx] = opt;
                      setResponses(c);
                    }}
                    className={`w-full text-left p-4 rounded-xl border-2 transition-all flex items-center justify-between
                      ${selected
                        ? "border-primary bg-primary/15 glow-blue"
                        : "border-white/10 bg-white/[0.03] hover:border-white/25"}`}
                  >
                    <span className="text-sm md:text-base">{opt}</span>
                    {selected && <CheckCircle2 className="w-5 h-5 text-primary shrink-0" />}
                  </button>
                );
              })}
            </div>
          ) : (
            <Input
              autoFocus
              value={value}
              onChange={(e) => {
                const c = [...responses];
                c[idx] = e.target.value;
                setResponses(c);
              }}
              maxLength={60}
              placeholder="Type your answer…"
              className="h-14 text-base"
            />
          )}
        </motion.div>
      </AnimatePresence>

      <div className="flex gap-3 pt-2">
        <Button type="button" variant="glass" size="lg" onClick={prev}>
          <ArrowLeft className="w-4 h-4" />
        </Button>
        <Button variant="hero" size="lg" disabled={!canNext} onClick={next} className="flex-1">
          {idx === QUESTIONS.length - 1 ? "Submit Quiz" : "Next"}
          <ArrowRight className="ml-1 w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}