'use client';

import { useState, useEffect, useCallback } from 'react';
import QuestionCard from './QuestionCard';
import ProgressBar from './ProgressBar';
import SuccessScreen from './SuccessScreen';
import type { Question, QuestionState } from '../../types';

interface ExamPageProps {
  examId: string;
  examTitle: string;
  examDescription: string;
  questions: Question[];
}

export default function ExamPage({
  examId,
  examTitle,
  examDescription,
  questions,
}: ExamPageProps) {
  const [questionStates, setQuestionStates] = useState<QuestionState[]>([]);
  const [examCompleted, setExamCompleted] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    setQuestionStates(
      questions.map((q) => ({
        questionId: q.id,
        selectedAnswer: null,
        status: 'unanswered' as const,
      }))
    );
  }, [questions]);

  const correctCount = questionStates.filter(
    (state) => state.status === 'correct'
  ).length;

  useEffect(() => {
    if (questions.length > 0 && correctCount === questions.length) {
      setExamCompleted(true);
    }
  }, [correctCount, questions.length]);

  const handleAnswerSelect = useCallback(
    async (questionId: string, answer: string) => {
      try {
        const response = await fetch('/api/check-answer', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            questionId,
            selectedAnswer: answer,
          }),
        });

        const data = await response.json();

        if (response.ok) {
          setQuestionStates((prev) =>
            prev.map((state) =>
              state.questionId === questionId
                ? {
                    ...state,
                    selectedAnswer: answer,
                    status: data.correct ? 'correct' : 'incorrect',
                  }
                : state
            )
          );
        } else {
          console.error('Error checking answer:', data.error);
        }
      } catch (error) {
        console.error('Error checking answer:', error);
      }
    },
    []
  );

  const handleRestart = () => {
    setQuestionStates(
      questions.map((q) => ({
        questionId: q.id,
        selectedAnswer: null,
        status: 'unanswered' as const,
      }))
    );
    setExamCompleted(false);
    setCurrentIndex(0);
  };

  if (questions.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="text-center">
          <div className="text-6xl mb-4">📭</div>
          <p className="text-gray-600">این آزمون هنوز سوالی ندارد</p>
        </div>
      </div>
    );
  }

  if (examCompleted) {
    return <SuccessScreen onRestart={handleRestart} totalQuestions={questions.length} />;
  }

  const currentQuestion = questions[currentIndex];
  const currentState = questionStates.find(
    (state) => state.questionId === currentQuestion?.id
  );

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-3xl mx-auto px-4 py-8">
        <div className="mb-8 text-center">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">{examTitle}</h1>
          {examDescription && (
            <p className="text-gray-600">{examDescription}</p>
          )}
        </div>

        <div className="card mb-6">
          <ProgressBar
            current={currentIndex + 1}
            total={questions.length}
            correctCount={correctCount}
          />
        </div>

        <div className="flex gap-2 mb-6 flex-wrap justify-center">
          {questions.map((question, index) => {
            const state = questionStates.find(
              (s) => s.questionId === question.id
            );
            return (
              <button
                key={question.id}
                onClick={() => setCurrentIndex(index)}
                className={`w-10 h-10 rounded-lg text-sm font-medium transition-all ${
                  currentIndex === index
                    ? 'bg-indigo-600 text-white ring-2 ring-indigo-300'
                    : state?.status === 'correct'
                    ? 'bg-green-500 text-white'
                    : state?.status === 'incorrect'
                    ? 'bg-red-500 text-white'
                    : 'bg-white text-gray-700 border border-gray-300'
                }`}
              >
                {index + 1}
              </button>
            );
          })}
        </div>

        {currentQuestion && currentState && (
          <QuestionCard
            key={currentQuestion.id}
            question={currentQuestion}
            index={currentIndex}
            total={questions.length}
            selectedAnswer={currentState.selectedAnswer}
            status={currentState.status}
            onAnswerSelect={handleAnswerSelect}
          />
        )}

        <div className="flex justify-between gap-4 mt-6">
          <button
            onClick={() => setCurrentIndex((prev) => Math.max(0, prev - 1))}
            disabled={currentIndex === 0}
            className="btn-secondary disabled:opacity-30"
          >
            سوال قبلی
          </button>
          <button
            onClick={() => setCurrentIndex((prev) => Math.min(questions.length - 1, prev + 1))}
            disabled={currentIndex === questions.length - 1}
            className="btn-primary disabled:opacity-30"
          >
            سوال بعدی
          </button>
        </div>
      </div>
    </div>
  );
}
