import { useState } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';

type Subject = {
  id: number;
  name: string;
  code: string;
  weeklyHours: string | number;
  defaultMaxScore: string | number;
  passingScore: string | number;
  status: string;
};

type Props = {
  subjects: Subject[];
};

const blank = { name: '', code: '', weekly_hours: '', default_max_score: '20', passing_score: '' };

export default function Subjects({ subjects }: Props) {
  const [editId, setEditId] = useState<number | null>(null);
  const form = useForm({ ...blank });

  function startEdit(subject: Subject) {
    setEditId(subject.id);
    form.setData({
      name: subject.name,
      code: subject.code,
      weekly_hours: subject.weeklyHours ? String(subject.weeklyHours) : '',
      default_max_score: subject.defaultMaxScore ? String(subject.defaultMaxScore) : '20',
      passing_score: subject.passingScore ? String(subject.passingScore) : '',
    });
    document.getElementById('subject-form')?.scrollIntoView({ behavior: 'smooth' });
  }

  function cancelEdit() {
    setEditId(null);
    form.reset();
    form.clearErrors();
  }

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (editId) {
      form.put(`/school/subjects/${editId}`, {
        preserveScroll: true,
        onSuccess: () => { form.reset(); setEditId(null); },
      });
    } else {
      form.post('/school/subjects', {
        preserveScroll: true,
        onSuccess: () => form.reset(),
      });
    }
  }

  function handleDelete(subject: Subject) {
    if (!confirm(`آیا می‌خواهید درس «${subject.name}» را حذف کنید؟`)) return;
    router.delete(`/school/subjects/${subject.id}`, { preserveScroll: true });
  }

  return (
    <AppLayout title="درس‌ها">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>مدیریت درس‌ها</h2>
            <p>درس‌های تعریف‌شده در برنامه هفتگی، امتحانات و نمره‌دهی استفاده می‌شوند.</p>
          </div>
        </section>

        <form id="subject-form" className="panel-card" onSubmit={handleSubmit}>
          <h2>{editId ? 'ویرایش درس' : 'افزودن درس'}</h2>
          <div className="form-grid">
            <TextInput label="نام درس" placeholder="مثلا ریاضی" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} error={form.errors.name} />
            <TextInput label="کد درس" placeholder="اختیاری" value={form.data.code} onChange={(e) => form.setData('code', e.target.value)} error={form.errors.code} />
            <TextInput label="ساعت در هفته" type="number" min="1" value={form.data.weekly_hours} onChange={(e) => form.setData('weekly_hours', e.target.value)} error={form.errors.weekly_hours} />
            <TextInput label="حداکثر نمره" type="number" min="1" step="0.25" value={form.data.default_max_score} onChange={(e) => form.setData('default_max_score', e.target.value)} error={form.errors.default_max_score} />
            <TextInput label="حد قبولی" type="number" min="0" step="0.25" value={form.data.passing_score} onChange={(e) => form.setData('passing_score', e.target.value)} error={form.errors.passing_score} />
          </div>
          <div className="action-row">
            <button className="btn btn-primary" disabled={form.processing} type="submit">
              <i className={`bi ${editId ? 'bi-pencil-square' : 'bi-plus-square'}`} />
              {editId ? 'ذخیره تغییرات' : 'ثبت درس'}
            </button>
            {editId && (
              <button className="btn btn-ghost" type="button" onClick={cancelEdit}>
                انصراف
              </button>
            )}
          </div>
        </form>

        {subjects.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>نام درس</th>
                  <th>کد</th>
                  <th>ساعت/هفته</th>
                  <th>نمره کامل</th>
                  <th>حد قبولی</th>
                  <th>وضعیت</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {subjects.map((subject) => (
                  <tr key={subject.id} className={editId === subject.id ? 'row-editing' : ''}>
                    <td>{subject.name}</td>
                    <td>{subject.code || '—'}</td>
                    <td>{subject.weeklyHours || '—'}</td>
                    <td>{subject.defaultMaxScore || 20}</td>
                    <td>{subject.passingScore || '—'}</td>
                    <td>{subject.status}</td>
                    <td>
                      <div className="action-row action-row--compact">
                        <button className="btn btn-ghost btn-sm" type="button" onClick={() => startEdit(subject)}>
                          <i className="bi bi-pencil" />
                        </button>
                        <button className="btn btn-danger-ghost btn-sm" type="button" onClick={() => handleDelete(subject)}>
                          <i className="bi bi-trash" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز درسی تعریف نشده</h2>
            <p>درس‌ها در برنامه هفتگی، امتحانات و نمره‌دهی استفاده می‌شوند. از فرم بالا شروع کن.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
