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

type StudentRow = {
  id: number;
  fullName: string;
  firstName: string;
  lastName: string;
  studentCode: string;
  mobile: string;
  fatherMobile: string;
  motherMobile: string;
  homePhone: string;
  address: string;
  gradeLevelId: number | null;
  classroomId: number | null;
  grade: string;
  profileStatus: string;
  lastSeen: string;
};

type Props = {
  metrics: { total: number; incomplete: number; onlineToday: number };
  students: StudentRow[];
  gradeOptions: Array<{ value: string | number; label: string }>;
  classroomOptions: Array<{ value: string | number; label: string }>;
};

const blank = {
  student_code: '',
  first_name: '',
  last_name: '',
  mobile: '',
  father_mobile: '',
  mother_mobile: '',
  home_phone: '',
  address: '',
  grade_level_id: '',
  classroom_id: '',
};

export default function Students({ metrics, students, gradeOptions, classroomOptions }: Props) {
  const [editId, setEditId] = useState<number | null>(null);
  const form = useForm({ ...blank });

  function startEdit(student: StudentRow) {
    setEditId(student.id);
    form.setData({
      student_code: student.studentCode,
      first_name: student.firstName,
      last_name: student.lastName,
      mobile: student.mobile,
      father_mobile: student.fatherMobile,
      mother_mobile: student.motherMobile,
      home_phone: student.homePhone,
      address: student.address,
      grade_level_id: student.gradeLevelId ? String(student.gradeLevelId) : '',
      classroom_id: student.classroomId ? String(student.classroomId) : '',
    });
    document.getElementById('student-form')?.scrollIntoView({ behavior: 'smooth' });
  }

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

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

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

  return (
    <AppLayout title="دانش‌آموزان">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>پرونده دانش‌آموزان</h2>
            <p>مدیریت اطلاعات، وضعیت تکمیل پروفایل، شماره‌های تماس پدر/مادر و آمار آنلاین بودن.</p>
          </div>
          <div className="action-row">
            <a className="btn btn-soft" href="/school/import/students"><i className="bi bi-upload" /> Import CSV</a>
            <a className="btn btn-ghost" href="/school/exports"><i className="bi bi-download" /> Export</a>
          </div>
        </section>

        <form id="student-form" className="panel-card" onSubmit={handleSubmit}>
          <h2>{editId ? 'ویرایش دانش‌آموز' : 'افزودن دانش‌آموز'}</h2>
          <div className="form-grid">
            <TextInput label="کد دانش‌آموزی" value={form.data.student_code} onChange={(e) => form.setData('student_code', e.target.value)} error={form.errors.student_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} />
            <SelectInput label="پایه" value={form.data.grade_level_id} onChange={(e) => form.setData('grade_level_id', e.target.value)} options={[{ value: '', label: 'انتخاب پایه' }, ...gradeOptions]} />
            <SelectInput label="کلاس" value={form.data.classroom_id} onChange={(e) => form.setData('classroom_id', e.target.value)} options={[{ value: '', label: 'بدون کلاس' }, ...classroomOptions]} />
            <TextInput label="موبایل دانش‌آموز" value={form.data.mobile} onChange={(e) => form.setData('mobile', e.target.value)} error={form.errors.mobile} />
            <TextInput label="موبایل پدر" value={form.data.father_mobile} onChange={(e) => form.setData('father_mobile', e.target.value)} error={form.errors.father_mobile} />
            <TextInput label="موبایل مادر" value={form.data.mother_mobile} onChange={(e) => form.setData('mother_mobile', e.target.value)} error={form.errors.mother_mobile} />
            <TextInput label="شماره خانه" value={form.data.home_phone} onChange={(e) => form.setData('home_phone', e.target.value)} />
            <TextInput label="آدرس" value={form.data.address} onChange={(e) => form.setData('address', 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-plus'}`} />
              {editId ? 'ذخیره تغییرات' : 'ثبت دانش‌آموز'}
            </button>
            {editId && (
              <button className="btn btn-ghost" type="button" onClick={cancelEdit}>
                انصراف
              </button>
            )}
          </div>
        </form>

        <section className="dashboard-grid">
          <article className="metric-card"><span>کل دانش‌آموزان</span><strong>{formatCount(metrics.total)}</strong></article>
          <article className="metric-card"><span>پروفایل ناقص</span><strong>{formatCount(metrics.incomplete)}</strong></article>
          <article className="metric-card"><span>آنلاین امروز</span><strong>{formatCount(metrics.onlineToday)}</strong></article>
        </section>

        {students.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>
                {students.map((student) => (
                  <tr key={student.id} className={editId === student.id ? 'row-editing' : ''}>
                    <td>{student.fullName}</td>
                    <td>{student.studentCode}</td>
                    <td>{student.grade}</td>
                    <td>{student.profileStatus}</td>
                    <td>{student.lastSeen}</td>
                    <td>
                      <div className="action-row action-row--compact">
                        <button className="btn btn-ghost btn-sm" type="button" onClick={() => startEdit(student)}>
                          <i className="bi bi-pencil" />
                        </button>
                        <button className="btn btn-danger-ghost btn-sm" type="button" onClick={() => handleDelete(student)}>
                          <i className="bi bi-trash" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز دانش‌آموزی ثبت نشده</h2>
            <p>از فرم بالا یا Import CSV برای اضافه کردن دانش‌آموز استفاده کن.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
