'use client';

import { useState } from 'react';
import AnswerOption from './AnswerOption';
import type { Question } from '../../types';

interface QuestionCardProps {
  question: Question;
  index: number;
  total: number;
  selectedAnswer: string | null;
  status: 'correct' | 'incorrect' | 'unanswered';
  onAnswerSelect: (questionId: string, answer: string) => void;
}

export default function QuestionCard({
  question,
  index,
  total,
  selectedAnswer,
  status,
  onAnswerSelect,
}: QuestionCardProps) {
  const [checkingAnswer, setCheckingAnswer] = useState(false);

  const handleAnswerClick = async (answer: string) => {
    if (status === 'correct') return;
    if (checkingAnswer) return;

    setCheckingAnswer(true);
    await onAnswerSelect(question.id, answer);
    setCheckingAnswer(false);
  };

  const getOptionState = (label: string): 'default' | 'correct' | 'incorrect' | 'show-correct' => {
    if (status === 'correct' && selectedAnswer === label) {
      return 'correct';
    }
    if (status === 'incorrect' && selectedAnswer === label) {
      return 'incorrect';
    }
    if (status === 'incorrect' && question.correctAnswer === label) {
      return 'show-correct';
    }
    return 'default';
  };

  const options = ['A', 'B', 'C', 'D'].map((label) => ({
    label,
    text: question.options[label.charCodeAt(0) - 65],
  }));

  return (
    <div className="card animate-slide-up">
      <div className="mb-6">
        <div className="flex items-center gap-3 mb-4">
          <span className="w-8 h-8 flex items-center justify-center bg-indigo-100 text-indigo-700 font-bold rounded-lg">
            {index + 1}
          </span>
          <span className="text-sm text-gray-500">
            از {total} سوال
          </span>
        </div>
        <h2 className="text-lg md:text-xl font-medium text-gray-900">
          {question.text}
        </h2>
      </div>

      <div className="space-y-3">
        {options.map((option) => (
          <AnswerOption
            key={option.label}
            label={option.label}
            text={option.text}
            state={getOptionState(option.label)}
            onClick={() => handleAnswerClick(option.label)}
            disabled={status === 'correct' || checkingAnswer}
          />
        ))}
      </div>

      {status === 'correct' && (
        <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
          ✓ پاسخ صحیح! آفرین!
        </div>
      )}

      {status === 'incorrect' && (
        <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
          ✗ پاسخ اشتباه بود. گزینه صحیح با رنگ سبز مشخص شده است. لطفاً دوباره تلاش کنید.
        </div>
      )}
    </div>
  );
}
