import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, CardHeader } from '../../ui/Card';
import { Button } from '../../ui/Button';
import { CheckCircle, XCircle, ArrowRight, Lightbulb } from 'lucide-react';

export interface QuizOption {
  id: string;
  text: string;
  isCorrect: boolean;
}

export interface QuizHint {
  text: string;
}

export interface QuizExerciseProps {
  question: string;
  questionNumber?: number;
  totalQuestions?: number;
  options: QuizOption[];
  hints?: QuizHint[];
  explanation: string;
  onComplete?: (result: QuizResult) => void;
  exerciseId?: string;
  maxAttempts?: number;
}

export interface QuizResult {
  correct: boolean;
  attempts: number;
  score: number;
  maxScore: number;
  usedHint: boolean;
}

const MAX_SCORE_PER_QUESTION = 100;
const HINT_PENALTY = 20;
const ATTEMPTS_BEFORE_HINT = 2;

export function QuizExercise({
  question,
  questionNumber,
  totalQuestions,
  options,
  hints = [],
  explanation,
  onComplete,
  exerciseId: _exerciseId,
  maxAttempts = 3,
}: QuizExerciseProps) {
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const [showFeedback, setShowFeedback] = useState(false);
  const [attempts, setAttempts] = useState(0);
  const [showHint, setShowHint] = useState(false);
  const [hintIndex, setHintIndex] = useState(0);
  const [currentHint, setCurrentHint] = useState<string | null>(null);
  const [isComplete, setIsComplete] = useState(false);
  const [score, setScore] = useState(0);
  const [usedHint, setUsedHint] = useState(false);

  const correctOption = options.find((opt) => opt.isCorrect);
  const isCorrect = selectedOption === correctOption?.id;

  useEffect(() => {
    if (isComplete && onComplete) {
      const maxScore = MAX_SCORE_PER_QUESTION;
      onComplete({
        correct: isCorrect,
        attempts,
        score,
        maxScore,
        usedHint,
      });
    }
  }, [isComplete, onComplete, isCorrect, attempts, score, usedHint]);

  const handleSelectOption = (optionId: string) => {
    if (showFeedback) return;
    setSelectedOption(optionId);
  };

  const handleSubmit = () => {
    if (!selectedOption || showFeedback) return;

    setShowFeedback(true);
    setAttempts((prev) => prev + 1);

    if (selectedOption === correctOption?.id) {
      // Calculate score based on attempts
      let earnedScore = MAX_SCORE_PER_QUESTION;
      if (attempts > 0) {
        // Reduce score for each attempt (except first)
        earnedScore = Math.max(MAX_SCORE_PER_QUESTION - (attempts * 20), 20);
      }
      if (usedHint) {
        earnedScore -= HINT_PENALTY;
      }
      setScore(earnedScore);
    }
  };

  const handleNext = () => {
    setIsComplete(true);
  };

  const handleRetry = () => {
    setSelectedOption(null);
    setShowFeedback(false);
    setAttempts(0);
    setShowHint(false);
    setHintIndex(0);
    setCurrentHint(null);
    setIsComplete(false);
    setScore(0);
    setUsedHint(false);
  };

  const handleShowHint = () => {
    if (hints.length === 0) return;

    setUsedHint(true);
    setShowHint(true);

    if (hintIndex < hints.length) {
      setCurrentHint(hints[hintIndex].text);
      setHintIndex((prev) => prev + 1);
    }
  };

  const canShowHint = hints.length > 0 && attempts >= ATTEMPTS_BEFORE_HINT && !showHint;

  // Determine if the user can continue or should retry
  const canRetry = attempts < maxAttempts && !isCorrect;

  if (isComplete) {
    return (
      <Card className="w-full max-w-2xl mx-auto">
        <div className="text-center py-8">
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: 'spring', stiffness: 200 }}
            className={`inline-flex items-center justify-center w-20 h-20 rounded-full mb-4 ${
              isCorrect ? 'bg-green-100' : 'bg-red-100'
            }`}
          >
            {isCorrect ? (
              <CheckCircle size={40} className="text-green-600" />
            ) : (
              <XCircle size={40} className="text-red-600" />
            )}
          </motion.div>

          <h3 className="text-2xl font-bold text-gray-900 mb-2">
            {isCorrect ? '¡Correcto!' : 'Incorrecto'}
          </h3>

          <div className="bg-gray-50 rounded-lg p-4 mb-6">
            <p className="text-sm text-gray-600 mb-2">Explicación:</p>
            <p className="text-gray-800">{explanation}</p>
          </div>

          <div className="grid grid-cols-2 gap-4 mb-6">
            <div className="bg-blue-50 rounded-lg p-4">
              <p className="text-sm text-blue-600 mb-1">Intentos</p>
              <p className="text-2xl font-bold text-blue-700">{attempts}</p>
            </div>
            <div className="bg-green-50 rounded-lg p-4">
              <p className="text-sm text-green-600 mb-1">Puntuación</p>
              <p className="text-2xl font-bold text-green-700">
                {score}/{MAX_SCORE_PER_QUESTION}
              </p>
            </div>
          </div>

          {canRetry && !isCorrect && (
            <Button onClick={handleRetry} variant="outline">
              Intentar de Nuevo
            </Button>
          )}

          {!canRetry && !isCorrect && (
            <div className="mt-4">
              <p className="text-gray-600 mb-4">
                Has agotado tus intentos. La respuesta correcta era:{' '}
                <span className="font-semibold text-green-600">{correctOption?.text}</span>
              </p>
              <Button onClick={handleRetry} variant="outline">
                Reiniciar Ejercicio
              </Button>
            </div>
          )}
        </div>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <CardHeader
        title={question}
        subtitle={
          questionNumber && totalQuestions
            ? `Pregunta ${questionNumber} de ${totalQuestions}`
            : undefined
        }
      />

      {/* Progress bar for multi-question exercises */}
      {questionNumber && totalQuestions && (
        <div className="mb-6">
          <div className="flex justify-between text-sm text-gray-600 mb-2">
            <span>Progreso</span>
            <span>{Math.round((questionNumber / totalQuestions) * 100)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2.5">
            <motion.div
              className="bg-blue-600 h-2.5 rounded-full"
              initial={{ width: 0 }}
              animate={{ width: `${(questionNumber / totalQuestions) * 100}%` }}
              transition={{ duration: 0.3 }}
            />
          </div>
        </div>
      )}

      <div className="space-y-3 mb-6">
        {options.map((option, index) => {
          const isSelected = selectedOption === option.id;
          const showCorrect = showFeedback && option.isCorrect;
          const showIncorrect = showFeedback && isSelected && !option.isCorrect;

          return (
            <motion.button
              key={option.id}
              onClick={() => handleSelectOption(option.id)}
              disabled={showFeedback}
              whileHover={!showFeedback ? { scale: 1.02 } : {}}
              whileTap={!showFeedback ? { scale: 0.98 } : {}}
              className={`w-full p-4 rounded-lg border-2 text-left transition-all ${
                showCorrect
                  ? 'border-green-500 bg-green-50'
                  : showIncorrect
                  ? 'border-red-500 bg-red-50'
                  : isSelected
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-blue-300'
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <span className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-100 text-gray-700 font-semibold text-sm">
                    {String.fromCharCode(65 + index)}
                  </span>
                  <span className="font-medium">{option.text}</span>
                </div>
                {showCorrect && <CheckCircle size={20} className="text-green-600" />}
                {showIncorrect && <XCircle size={20} className="text-red-600" />}
              </div>
            </motion.button>
          );
        })}
      </div>

      {/* Hint section */}
      <AnimatePresence>
        {showHint && currentHint && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden mb-6"
          >
            <div className="p-4 rounded-lg border bg-yellow-50 border-yellow-200">
              <div className="flex items-center gap-2 mb-2">
                <Lightbulb size={20} className="text-yellow-600" />
                <span className="font-semibold text-yellow-800">Pista</span>
              </div>
              <p className="text-sm text-yellow-700">{currentHint}</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Feedback section */}
      <AnimatePresence>
        {showFeedback && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden mb-6"
          >
            <div
              className={`p-4 rounded-lg border ${
                isCorrect ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'
              }`}
            >
              <div className="flex items-center gap-2 mb-2">
                {isCorrect ? (
                  <CheckCircle size={20} className="text-green-600" />
                ) : (
                  <XCircle size={20} className="text-red-600" />
                )}
                <span
                  className={`font-semibold ${
                    isCorrect ? 'text-green-800' : 'text-red-800'
                  }`}
                >
                  {isCorrect ? '¡Correcto!' : 'Incorrecto'}
                </span>
              </div>
              <p className={`text-sm ${isCorrect ? 'text-green-700' : 'text-red-700'}`}>
                {explanation}
              </p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <div className="flex justify-between items-center">
        <div className="text-sm text-gray-600">
          <span>
            Intentos: <span className="font-bold">{attempts}</span>/{maxAttempts}
          </span>
          {canShowHint && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleShowHint}
              className="ml-2 text-yellow-600 hover:text-yellow-700"
            >
              <Lightbulb size={16} className="mr-1" />
              Ver pista
            </Button>
          )}
        </div>

        {!showFeedback ? (
          <Button onClick={handleSubmit} disabled={!selectedOption}>
            Validar Respuesta
          </Button>
        ) : (
          <Button onClick={handleNext}>
            {isCorrect ? (
              <>
                Continuar
                <ArrowRight size={16} className="ml-2" />
              </>
            ) : canRetry ? (
              <>
                Intentar de Nuevo
                <ArrowRight size={16} className="ml-2" />
              </>
            ) : (
              'Ver Resultado'
            )}
          </Button>
        )}
      </div>
    </Card>
  );
}

export default QuizExercise;
