'use client';

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

interface QuestionEditorProps {
  question?: Question;
  onSubmit: (data: any) => void;
  onCancel: () => void;
}

const OPTION_LABELS = ['A', 'B', 'C', 'D'] as const;

export default function QuestionEditor({
  question,
  onSubmit,
  onCancel,
}: QuestionEditorProps) {
  const [text, setText] = useState(question?.text || '');
  const [options, setOptions] = useState<string[]>(
    question?.options || ['', '', '', '']
  );
  const [correctAnswer, setCorrectAnswer] = useState<string>(
    question?.correctAnswer || 'A'
  );
  const [errors, setErrors] = useState<string[]>([]);

  const validate = (): boolean => {
    const newErrors: string[] = [];

    if (!text.trim()) {
      newErrors.push('متن سوال الزامی است');
    }

    options.forEach((opt, index) => {
      if (!opt.trim()) {
        newErrors.push(`گزینه ${OPTION_LABELS[index]} الزامی است`);
      }
    });

    setErrors(newErrors);
    return newErrors.length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!validate()) return;

    onSubmit({
      text: text.trim(),
      options: options.map((o) => o.trim()),
      correctAnswer,
    });
  };

  const handleOptionChange = (index: number, value: string) => {
    const newOptions = [...options];
    newOptions[index] = value;
    setOptions(newOptions);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {errors.length > 0 && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          <ul className="list-disc list-inside text-sm">
            {errors.map((error, index) => (
              <li key={index}>{error}</li>
            ))}
          </ul>
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          متن سوال *
        </label>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          className="input-field min-h-[80px] resize-y"
          placeholder="متن سوال را وارد کنید..."
        />
      </div>

      <div className="space-y-3">
        <label className="block text-sm font-medium text-gray-700">
          گزینه‌ها *
        </label>
        {OPTION_LABELS.map((label, index) => (
          <div key={label} className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              <input
                type="radio"
                id={`correct-${label}`}
                name="correctAnswer"
                value={label}
                checked={correctAnswer === label}
                onChange={(e) => setCorrectAnswer(e.target.value)}
                className="w-4 h-4 text-indigo-600 focus:ring-indigo-500"
              />
              <label
                htmlFor={`correct-${label}`}
                className="text-sm font-medium text-gray-700 cursor-pointer"
              >
                {label}.
              </label>
            </div>
            <input
              type="text"
              value={options[index]}
              onChange={(e) => handleOptionChange(index, e.target.value)}
              className="input-field flex-1"
              placeholder={`گزینه ${label}`}
            />
          </div>
        ))}
        <p className="text-xs text-gray-500">
          با انتخاب دکمه رادیویی، گزینه صحیح را مشخص کنید
        </p>
      </div>

      <div className="flex gap-3">
        <button type="submit" className="btn-primary flex-1">
          {question ? 'ذخیره تغییرات' : 'افزودن سوال'}
        </button>
        <button type="button" onClick={onCancel} className="btn-secondary">
          انصراف
        </button>
      </div>
    </form>
  );
}
