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

type Teacher = {
  id: number;
  fullName: string;
  firstName: string;
  lastName: string;
  teacherCode: string;
  specialty: string;
  mobile: string;
  email: string;
  classes: string;
  status: string;
};

type Props = {
  teachers: Teacher[];
};

const blank = {
  teacher_code: '',
  first_name: '',
  last_name: '',
  mobile: '',
  email: '',
  specialty: '',
};

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

  function startEdit(teacher: Teacher) {
    setEditId(teacher.id);
    form.setData({
      teacher_code: teacher.teacherCode,
      first_name: teacher.firstName,
      last_name: teacher.lastName,
      mobile: teacher.mobile,
      email: teacher.email,
      specialty: teacher.specialty,
    });
    document.getElementById('teacher-form')?.scrollIntoView({ behavior: 'smooth' });
  }

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

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

  function handleDelete(teacher: Teacher) {
    if (!confirm(`آیا می‌خواهید معلم «${teacher.fullName}» را حذف کنید؟`)) return;
    router.delete(`/school/teachers/${teacher.id}`, { preserveScroll: true });
  }

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

        <form id="teacher-form" className="panel-card" onSubmit={handleSubmit}>
          <h2>{editId ? 'ویرایش معلم' : 'افزودن معلم'}</h2>
          <div className="form-grid">
            <TextInput label="کد معلم" value={form.data.teacher_code} onChange={(e) => form.setData('teacher_code', e.target.value)} error={form.errors.teacher_code} />
            <TextInput label="نام" value={form.data.first_name} onChange={(e) => form.setData('first_name', e.target.value)} error={form.errors.first_name} />
            <TextInput label="نام خانوادگی" value={form.data.last_name} onChange={(e) => form.setData('last_name', e.target.value)} error={form.errors.last_name} />
            <TextInput label="موبایل" value={form.data.mobile} onChange={(e) => form.setData('mobile', e.target.value)} error={form.errors.mobile} />
            <TextInput label="ایمیل" value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} error={form.errors.email} />
            <TextInput label="تخصص / درس اصلی" value={form.data.specialty} onChange={(e) => form.setData('specialty', e.target.value)} />
          </div>
          <div className="action-row">
            <button className="btn btn-primary" disabled={form.processing} type="submit">
              <i className={`bi ${editId ? 'bi-pencil-square' : 'bi-person-workspace'}`} />
              {editId ? 'ذخیره تغییرات' : 'ثبت معلم'}
            </button>
            {editId && (
              <button className="btn btn-ghost" type="button" onClick={cancelEdit}>
                انصراف
              </button>
            )}
          </div>
        </form>

        {teachers.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>نام</th>
                  <th>تخصص/درس</th>
                  <th>کلاس‌ها</th>
                  <th>موبایل</th>
                  <th>وضعیت</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {teachers.map((teacher) => (
                  <tr key={teacher.id} className={editId === teacher.id ? 'row-editing' : ''}>
                    <td>{teacher.fullName}</td>
                    <td>{teacher.specialty || '—'}</td>
                    <td>{teacher.classes}</td>
                    <td>{teacher.mobile || '—'}</td>
                    <td>{teacher.status}</td>
                    <td>
                      <div className="action-row action-row--compact">
                        <button className="btn btn-ghost btn-sm" type="button" onClick={() => startEdit(teacher)}>
                          <i className="bi bi-pencil" />
                        </button>
                        <button className="btn btn-danger-ghost btn-sm" type="button" onClick={() => handleDelete(teacher)}>
                          <i className="bi bi-trash" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز معلمی ثبت نشده</h2>
            <p>بعد از ساخت معلم یا import، داده واقعی این جدول از دیتابیس می‌آید.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
