'use client';

import { useState } from 'react';
import QuestionEditor from './QuestionEditor';
import type { Exam, Question } from '../../types';

interface ExamEditorProps {
  exam: Exam;
  questions: Question[];
  onExamUpdate: (exam: Exam) => void;
  onQuestionsUpdate: (questions: Question[]) => void;
  onRefresh: () => void;
}

export default function ExamEditor({
  exam,
  questions,
  onExamUpdate,
  onQuestionsUpdate,
  onRefresh,
}: ExamEditorProps) {
  const [showAddQuestion, setShowAddQuestion] = useState(false);
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);
  const [savingExam, setSavingExam] = useState(false);

  const handleSaveExam = async () => {
    setSavingExam(true);
    try {
      const response = await fetch(`/api/exams/${exam.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: exam.title,
          description: exam.description,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        onExamUpdate(data.exam);
        alert('آزمون با موفقیت ذخیره شد');
      } else {
        const data = await response.json();
        alert(data.error || 'خطا در ذخیره آزمون');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور');
    } finally {
      setSavingExam(false);
    }
  };

  const handleAddQuestion = async (questionData: any) => {
    try {
      const response = await fetch('/api/questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...questionData,
          examId: exam.id,
        }),
      });

      if (response.ok) {
        onRefresh();
        setShowAddQuestion(false);
      } else {
        const data = await response.json();
        alert(data.error || 'خطا در افزودن سوال');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور');
    }
  };

  const handleUpdateQuestion = async (questionId: string, questionData: any) => {
    try {
      const response = await fetch(`/api/questions/${questionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(questionData),
      });

      if (response.ok) {
        onRefresh();
        setEditingQuestion(null);
      } else {
        const data = await response.json();
        alert(data.error || 'خطا در ویرایش سوال');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور');
    }
  };

  const handleDeleteQuestion = async (questionId: string) => {
    if (!confirm('آیا از حذف این سوال مطمئن هستید؟')) return;

    try {
      const response = await fetch(`/api/questions/${questionId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        onRefresh();
      } else {
        const data = await response.json();
        alert(data.error || 'خطا در حذف سوال');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور');
    }
  };

  const handleMoveQuestion = async (questionId: string, direction: 'up' | 'down') => {
    const index = questions.findIndex((q) => q.id === questionId);
    if (index === -1) return;

    const newIndex = direction === 'up' ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= questions.length) return;

    const newQuestions = [...questions];
    [newQuestions[index], newQuestions[newIndex]] = [newQuestions[newIndex], newQuestions[index]];

    const questionIds = newQuestions.map((q) => q.id);

    try {
      const response = await fetch('/api/reorder-questions', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ questionIds }),
      });

      if (response.ok) {
        onQuestionsUpdate(newQuestions);
      }
    } catch (err) {
      alert('خطا در تغییر ترتیب سوالات');
    }
  };

  return (
    <div className="space-y-6">
      <div className="card">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">جزئیات آزمون</h2>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              عنوان آزمون
            </label>
            <input
              type="text"
              value={exam.title}
              onChange={(e) => onExamUpdate({ ...exam, title: e.target.value })}
              className="input-field"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              توضیحات آزمون
            </label>
            <textarea
              value={exam.description}
              onChange={(e) => onExamUpdate({ ...exam, description: e.target.value })}
              className="input-field min-h-[80px] resize-y"
            />
          </div>
          <button onClick={handleSaveExam} className="btn-primary" disabled={savingExam}>
            {savingExam ? 'در حال ذخیره...' : 'ذخیره تغییرات'}
          </button>
        </div>
      </div>

      <div className="card">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold text-gray-900">
            سوالات ({questions.length})
          </h2>
          <button
            onClick={() => setShowAddQuestion(!showAddQuestion)}
            className="btn-primary"
          >
            {showAddQuestion ? 'انصراف' : '+ افزودن سوال'}
          </button>
        </div>

        {showAddQuestion && (
          <div className="mb-6 p-4 bg-gray-50 rounded-lg">
            <QuestionEditor
              onSubmit={handleAddQuestion}
              onCancel={() => setShowAddQuestion(false)}
            />
          </div>
        )}

        {questions.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-gray-600">هنوز سوالی اضافه نشده است</p>
          </div>
        ) : (
          <div className="space-y-4">
            {questions.map((question, index) => (
              <div key={question.id} className="border border-gray-200 rounded-lg p-4">
                {editingQuestion?.id === question.id ? (
                  <QuestionEditor
                    question={question}
                    onSubmit={(data) => handleUpdateQuestion(question.id, data)}
                    onCancel={() => setEditingQuestion(null)}
                  />
                ) : (
                  <div>
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <p className="font-medium text-gray-900 mb-2">
                          <span className="text-indigo-600 font-bold ml-2">
                            {index + 1}.
                          </span>
                          {question.text}
                        </p>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                          {(['A', 'B', 'C', 'D'] as const).map((label) => (
                            <div
                              key={label}
                              className={`text-sm px-3 py-2 rounded ${
                                question.correctAnswer === label
                                  ? 'bg-green-50 text-green-700 font-medium'
                                  : 'bg-gray-50 text-gray-600'
                              }`}
                            >
                              <span className="font-bold ml-1">{label}.</span>
                              {question.options[label.charCodeAt(0) - 65]}
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="flex flex-col gap-2">
                        <button
                          onClick={() => handleMoveQuestion(question.id, 'up')}
                          disabled={index === 0}
                          className="btn-secondary text-sm py-1 px-3 disabled:opacity-30"
                        >
                          ↑
                        </button>
                        <button
                          onClick={() => handleMoveQuestion(question.id, 'down')}
                          disabled={index === questions.length - 1}
                          className="btn-secondary text-sm py-1 px-3 disabled:opacity-30"
                        >
                          ↓
                        </button>
                        <button
                          onClick={() => setEditingQuestion(question)}
                          className="btn-secondary text-sm py-1 px-3"
                        >
                          ویرایش
                        </button>
                        <button
                          onClick={() => handleDeleteQuestion(question.id)}
                          className="btn-danger text-sm py-1 px-3"
                        >
                          حذف
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
