import React, { useState } from 'react';
import { Button } from '../../ui/button';
import { Quiz } from '../../../types';
import { X, CheckCircle, AlertCircle, HelpCircle } from 'lucide-react';

interface QuizModalProps {
  quiz: Quiz;
  onClose: () => void;
  onComplete: (score: number) => void;
}

export const QuizModal: React.FC<QuizModalProps> = ({
  quiz,
  onClose,
  onComplete,
}) => {
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswers, setSelectedAnswers] = useState<number[]>(
    new Array(quiz.questions.length).fill(-1),
  );
  const [showResults, setShowResults] = useState(false);

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

  const handleAnswerSelect = (index: number) => {
    const newAnswers = [...selectedAnswers];
    newAnswers[currentQuestionIndex] = index;
    setSelectedAnswers(newAnswers);
  };

  const handleNext = () => {
    if (currentQuestionIndex < quiz.questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    } else {
      setShowResults(true);
    }
  };

  const calculateScore = () => {
    let correct = 0;
    quiz.questions.forEach((q, i) => {
      if (selectedAnswers[i] === q.correctIndex) correct++;
    });
    return Math.round((correct / quiz.questions.length) * 100);
  };

  const score = calculateScore();
  const passed = score >= quiz.passingScore;

  const handleFinish = () => {
    onComplete(score);
    onClose();
  };

  if (showResults) {
    return (
      <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
        <div
          className="absolute inset-0 bg-kodo-void/90 backdrop-blur-sm"
          onClick={handleFinish}
        ></div>
        <div className="relative w-full max-w-md bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl animate-scaleIn overflow-hidden p-8 text-center">
          <div className="mb-6 flex justify-center">
            {passed ? (
              <div className="w-20 h-20 bg-kodo-lime/20 rounded-full flex items-center justify-center text-kodo-lime border-2 border-kodo-lime animate-pulse">
                <CheckCircle className="w-10 h-10" />
              </div>
            ) : (
              <div className="w-20 h-20 bg-kodo-red/20 rounded-full flex items-center justify-center text-kodo-red border-2 border-kodo-red">
                <AlertCircle className="w-10 h-10" />
              </div>
            )}
          </div>

          <h2 className="text-2xl font-bold text-white mb-2">
            {passed ? 'Assessment Passed!' : 'Try Again'}
          </h2>
          <p className="text-gray-400 mb-6">
            You scored{' '}
            <span
              className={`font-bold ${passed ? 'text-kodo-lime' : 'text-kodo-red'}`}
            >
              {score}%
            </span>
            .
            {passed
              ? ' Great job!'
              : ` You need ${quiz.passingScore}% to pass.`}
          </p>

          <Button
            variant={passed ? 'primary' : 'secondary'}
            className="w-full"
            onClick={handleFinish}
          >
            {passed ? 'Continue Learning' : 'Review Material'}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-kodo-void/90 backdrop-blur-sm"></div>
      <div className="relative w-full max-w-2xl bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl animate-scaleIn overflow-hidden flex flex-col max-h-[80vh]">
        {/* Header */}
        <div className="p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center">
          <h3 className="font-bold text-white flex items-center gap-2">
            <HelpCircle className="w-5 h-5 text-kodo-cyan" /> {quiz.title}
          </h3>
          <button onClick={onClose}>
            <X className="w-5 h-5 text-gray-400 hover:text-white" />
          </button>
        </div>

        {/* Progress */}
        <div className="h-1 bg-kodo-steel w-full">
          <div
            className="h-full bg-kodo-cyan transition-all duration-300"
            style={{
              width: `${((currentQuestionIndex + 1) / quiz.questions.length) * 100}%`,
            }}
          ></div>
        </div>

        {/* Question Area */}
        <div className="p-8 flex-1 overflow-y-auto">
          <span className="text-xs font-bold text-gray-500 uppercase mb-2 block">
            Question {currentQuestionIndex + 1} of {quiz.questions.length}
          </span>
          <h2 className="text-xl font-bold text-white mb-6 leading-relaxed">
            {currentQuestion.question}
          </h2>

          <div className="space-y-3">
            {currentQuestion.options.map((option, idx) => (
              <button
                key={idx}
                onClick={() => handleAnswerSelect(idx)}
                className={`w-full text-left p-4 rounded-lg border transition-all ${
                  selectedAnswers[currentQuestionIndex] === idx
                    ? 'bg-kodo-cyan/10 border-kodo-cyan text-white'
                    : 'bg-kodo-ink border-kodo-steel text-gray-300 hover:bg-white/5 hover:border-gray-500'
                }`}
              >
                <div className="flex items-center gap-3">
                  <div
                    className={`w-6 h-6 rounded-full border flex items-center justify-center text-xs font-bold ${selectedAnswers[currentQuestionIndex] === idx ? 'bg-kodo-cyan border-kodo-cyan text-black' : 'border-gray-500 text-gray-500'}`}
                  >
                    {String.fromCharCode(65 + idx)}
                  </div>
                  {option}
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-kodo-steel bg-kodo-ink flex justify-between items-center">
          <span className="text-xs text-gray-500">
            Passing Score: {quiz.passingScore}%
          </span>
          <Button
            variant="primary"
            onClick={handleNext}
            disabled={selectedAnswers[currentQuestionIndex] === -1}
          >
            {isLastQuestion ? 'Submit Quiz' : 'Next Question'}
          </Button>
        </div>
      </div>
    </div>
  );
};
