import React, { useState } from 'react';
import { QuizQuestion } from '../../types';
import { CheckCircle2, XCircle, ArrowRight, RotateCcw } from 'lucide-react';
import { motion } from 'motion/react';

interface QuizProps {
  questions: QuizQuestion[];
}

export function Quiz({ questions }: QuizProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [isAnswered, setIsAnswered] = useState(false);
  const [score, setScore] = useState(0);
  const [isFinished, setIsFinished] = useState(false);

  const currentQuestion = questions[currentIndex];

  const handleSelect = (index: number) => {
    if (isAnswered) return;
    setSelectedAnswer(index);
    setIsAnswered(true);
    
    if (index === currentQuestion.correctAnswerIndex) {
      setScore(prev => prev + 1);
    }
  };

  const handleNext = () => {
    if (currentIndex < questions.length - 1) {
      setCurrentIndex(prev => prev + 1);
      setSelectedAnswer(null);
      setIsAnswered(false);
    } else {
      setIsFinished(true);
    }
  };

  const handleReset = () => {
    setCurrentIndex(0);
    setSelectedAnswer(null);
    setIsAnswered(false);
    setScore(0);
    setIsFinished(false);
  };

  if (!questions || questions.length === 0) return null;

  if (isFinished) {
    const percentage = Math.round((score / questions.length) * 100);
    return (
      <div className="mx-auto flex h-full w-full max-w-[760px] flex-col items-center justify-center px-8 py-8 text-center">
        <div className="w-24 h-24 rounded-full bg-teal-500/10 flex items-center justify-center mb-6">
          <span className="text-4xl font-light text-teal-400">{percentage}%</span>
        </div>
        <h2 className="text-2xl font-medium text-zinc-100 mb-2">Quiz Completed</h2>
        <p className="text-zinc-400 mb-8">You scored {score} out of {questions.length} correctly.</p>
        <button
          onClick={handleReset}
          className="bg-white/5 hover:bg-white/10 text-zinc-200 rounded-lg px-6 py-3 text-sm font-medium flex items-center gap-2 transition-colors"
        >
          <RotateCcw size={16} />
          Retake Quiz
        </button>
      </div>
    );
  }

  return (
    <div className="mx-auto flex h-full w-full max-w-[960px] flex-col px-8 pb-8 pt-12">
      <div className="mb-12 flex items-center justify-between">
        <div>
          <h2 className="text-sm font-medium text-teal-500 uppercase tracking-widest mb-1">Knowledge Check</h2>
          <p className="text-zinc-400">Question {currentIndex + 1} of {questions.length}</p>
        </div>
        <div className="flex gap-1">
          {questions.map((_, idx) => (
            <div 
              key={idx} 
              className={`w-8 h-1 rounded-full ${
                idx < currentIndex ? 'bg-teal-500/50' : 
                idx === currentIndex ? 'bg-teal-500' : 'bg-white/5'
              }`}
            />
          ))}
        </div>
      </div>

      <div className="flex-1">
        <h3 className="text-2xl font-medium text-zinc-100 mb-8 leading-relaxed">
          {currentQuestion.question}
        </h3>

        <div className="space-y-3">
          {currentQuestion.options.map((option, index) => {
            const isSelected = selectedAnswer === index;
            const isCorrect = index === currentQuestion.correctAnswerIndex;
            const showCorrect = isAnswered && isCorrect;
            const showIncorrect = isAnswered && isSelected && !isCorrect;

            let buttonClass = "w-full text-left p-4 rounded-xl border transition-all flex items-center justify-between group ";
            
            if (!isAnswered) {
              buttonClass += "bg-white/5 border-white/5 hover:bg-white/10 hover:border-white/10 text-zinc-300";
            } else if (showCorrect) {
              buttonClass += "bg-teal-500/10 border-teal-500/50 text-teal-100";
            } else if (showIncorrect) {
              buttonClass += "bg-red-500/10 border-red-500/50 text-red-100";
            } else {
              buttonClass += "bg-white/5 border-transparent text-zinc-500 opacity-50";
            }

            return (
              <button
                key={index}
                onClick={() => handleSelect(index)}
                disabled={isAnswered}
                className={buttonClass}
              >
                <span className="text-lg">{option}</span>
                {showCorrect && <CheckCircle2 className="text-teal-500" size={20} />}
                {showIncorrect && <XCircle className="text-red-500" size={20} />}
              </button>
            );
          })}
        </div>

        {isAnswered && (
          <motion.div 
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mt-8 p-5 rounded-xl bg-[#131c2f] border border-white/5"
          >
            <h4 className="text-sm font-medium text-zinc-300 mb-2">Explanation</h4>
            <p className="text-zinc-400 leading-relaxed">{currentQuestion.explanation}</p>
            
            <div className="mt-6 flex justify-end">
              <button
                onClick={handleNext}
                className="bg-amber-600 hover:bg-amber-500 text-white rounded-lg px-6 py-2.5 text-sm font-medium flex items-center gap-2 transition-colors"
              >
                {currentIndex < questions.length - 1 ? 'Next Question' : 'Finish Quiz'}
                <ArrowRight size={16} />
              </button>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}
