'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function NewExamPage() {
  const router = useRouter();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    if (!title.trim()) {
      setError('عنوان آزمون الزامی است');
      return;
    }

    setLoading(true);

    try {
      const response = await fetch('/api/exams', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, description }),
      });

      const data = await response.json();

      if (response.ok) {
        router.push(`/admin/exams/${data.exam.id}/edit`);
      } else {
        setError(data.error || 'خطا در ایجاد آزمون');
      }
    } catch (err) {
      setError('خطا در ارتباط با سرور');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-3xl mx-auto px-4 py-8">
        <div className="mb-8">
          <Link href="/admin" className="text-indigo-600 hover:text-indigo-800 mb-4 inline-block">
            ← بازگشت به پنل مدیریت
          </Link>
          <h1 className="text-3xl font-bold text-gray-900">ایجاد آزمون جدید</h1>
        </div>

        <form onSubmit={handleSubmit} className="card space-y-6">
          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
              {error}
            </div>
          )}

          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-2">
              عنوان آزمون *
            </label>
            <input
              type="text"
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="input-field"
              placeholder="مثلاً: آزمون ریاضی فصل اول"
              required
            />
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-2">
              توضیحات آزمون
            </label>
            <textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="input-field min-h-[120px] resize-y"
              placeholder="توضیحات اختیاری درباره آزمون..."
            />
          </div>

          <div className="flex gap-4">
            <button type="submit" className="btn-primary flex-1" disabled={loading}>
              {loading ? 'در حال ایجاد...' : 'ایجاد آزمون'}
            </button>
            <Link href="/admin" className="btn-secondary">
              انصراف
            </Link>
          </div>
        </form>
      </div>
    </div>
  );
}
