/**
 * QuizQuestion Component
 * Renders a quiz question with various answer types
 */

import React from 'react';
import { Check, X, HelpCircle } from 'lucide-react';
import type { QuizQuestion as QuizQuestionType, QuestionResult } from '../../types/education.types';

interface QuizQuestionProps {
  question: QuizQuestionType;
  questionNumber: number;
  selectedAnswer: string | string[] | null;
  onAnswerChange: (answer: string | string[]) => void;
  showResult?: boolean;
  result?: QuestionResult;
  disabled?: boolean;
}

export const QuizQuestion: React.FC<QuizQuestionProps> = ({
  question,
  questionNumber,
  selectedAnswer,
  onAnswerChange,
  showResult = false,
  result,
  disabled = false,
}) => {
  const isMultipleAnswer = question.questionType === 'multiple_answer';
  const isTrueFalse = question.questionType === 'true_false';
  const isShortAnswer = question.questionType === 'short_answer';

  const handleOptionClick = (optionId: string) => {
    if (disabled) return;

    if (isMultipleAnswer) {
      const currentAnswers = Array.isArray(selectedAnswer) ? selectedAnswer : [];
      if (currentAnswers.includes(optionId)) {
        onAnswerChange(currentAnswers.filter((a) => a !== optionId));
      } else {
        onAnswerChange([...currentAnswers, optionId]);
      }
    } else {
      onAnswerChange(optionId);
    }
  };

  const isOptionSelected = (optionId: string) => {
    if (Array.isArray(selectedAnswer)) {
      return selectedAnswer.includes(optionId);
    }
    return selectedAnswer === optionId;
  };

  const getOptionStyle = (optionId: string) => {
    const selected = isOptionSelected(optionId);
    const baseStyle =
      'flex items-center gap-3 p-4 rounded-lg border transition-all cursor-pointer';

    if (showResult && result) {
      const isCorrectOption = result.correctAnswer?.includes(optionId);
      const wasSelected = Array.isArray(result.userAnswer)
        ? result.userAnswer.includes(optionId)
        : result.userAnswer === optionId;

      if (isCorrectOption) {
        return `${baseStyle} bg-green-500/20 border-green-500/50 text-green-400`;
      }
      if (wasSelected && !isCorrectOption) {
        return `${baseStyle} bg-red-500/20 border-red-500/50 text-red-400`;
      }
      return `${baseStyle} bg-gray-800 border-gray-700 text-gray-400`;
    }

    if (selected) {
      return `${baseStyle} bg-blue-500/20 border-blue-500/50 text-blue-400`;
    }

    return `${baseStyle} bg-gray-800 border-gray-700 text-gray-300 hover:border-gray-500`;
  };

  const trueFalseOptions = [
    { id: 'true', text: 'Verdadero' },
    { id: 'false', text: 'Falso' },
  ];

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
      {/* Question Header */}
      <div className="flex items-start justify-between mb-4">
        <div className="flex items-start gap-3">
          <span className="flex-shrink-0 w-8 h-8 rounded-full bg-blue-500/20 text-blue-400 flex items-center justify-center font-semibold text-sm">
            {questionNumber}
          </span>
          <div>
            <p className="text-white font-medium">{question.questionText}</p>
            <span className="text-xs text-gray-500 mt-1 block">
              {question.points} {question.points === 1 ? 'punto' : 'puntos'}
              {isMultipleAnswer && ' • Selección múltiple'}
            </span>
          </div>
        </div>

        {/* Result indicator */}
        {showResult && result && (
          <div
            className={`flex items-center gap-1 px-2 py-1 rounded text-sm ${
              result.isCorrect
                ? 'bg-green-500/20 text-green-400'
                : 'bg-red-500/20 text-red-400'
            }`}
          >
            {result.isCorrect ? (
              <>
                <Check className="w-4 h-4" />
                {result.pointsEarned}/{result.maxPoints}
              </>
            ) : (
              <>
                <X className="w-4 h-4" />
                0/{result.maxPoints}
              </>
            )}
          </div>
        )}
      </div>

      {/* Options */}
      <div className="space-y-3">
        {isTrueFalse ? (
          trueFalseOptions.map((option) => (
            <div
              key={option.id}
              className={getOptionStyle(option.id)}
              onClick={() => handleOptionClick(option.id)}
            >
              <div
                className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                  isOptionSelected(option.id)
                    ? 'border-blue-500 bg-blue-500'
                    : 'border-gray-500'
                }`}
              >
                {isOptionSelected(option.id) && <Check className="w-3 h-3 text-white" />}
              </div>
              <span>{option.text}</span>
            </div>
          ))
        ) : isShortAnswer ? (
          <div>
            <textarea
              value={(selectedAnswer as string) || ''}
              onChange={(e) => onAnswerChange(e.target.value)}
              disabled={disabled}
              placeholder="Escribe tu respuesta aquí..."
              className="w-full h-24 px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none resize-none disabled:opacity-50"
            />
            {showResult && result?.correctAnswer && (
              <div className="mt-2 p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
                <span className="text-xs text-green-400 font-medium">Respuesta correcta:</span>
                <p className="text-sm text-green-300 mt-1">{result.correctAnswer}</p>
              </div>
            )}
          </div>
        ) : (
          question.options?.map((option) => (
            <div
              key={option.id}
              className={getOptionStyle(option.id)}
              onClick={() => handleOptionClick(option.id)}
            >
              <div
                className={`w-5 h-5 ${
                  isMultipleAnswer ? 'rounded' : 'rounded-full'
                } border-2 flex items-center justify-center flex-shrink-0 ${
                  isOptionSelected(option.id)
                    ? 'border-blue-500 bg-blue-500'
                    : 'border-gray-500'
                }`}
              >
                {isOptionSelected(option.id) && <Check className="w-3 h-3 text-white" />}
              </div>
              <span className="flex-1">{option.text}</span>

              {/* Result icons */}
              {showResult && result && (
                <>
                  {result.correctAnswer?.includes(option.id) && (
                    <Check className="w-5 h-5 text-green-400" />
                  )}
                  {!result.correctAnswer?.includes(option.id) &&
                    (Array.isArray(result.userAnswer)
                      ? result.userAnswer.includes(option.id)
                      : result.userAnswer === option.id) && (
                      <X className="w-5 h-5 text-red-400" />
                    )}
                </>
              )}
            </div>
          ))
        )}
      </div>

      {/* Explanation (shown after answering) */}
      {showResult && result && question.explanation && (
        <div className="mt-4 p-4 bg-blue-500/10 border border-blue-500/30 rounded-lg">
          <div className="flex items-center gap-2 text-blue-400 mb-2">
            <HelpCircle className="w-4 h-4" />
            <span className="text-sm font-medium">Explicación</span>
          </div>
          <p className="text-sm text-gray-300">{question.explanation}</p>
        </div>
      )}

      {/* Feedback */}
      {showResult && result?.feedback && (
        <p className="mt-3 text-sm text-gray-400">{result.feedback}</p>
      )}
    </div>
  );
};

export default QuizQuestion;
