import { useRef, 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';
import { Pagination } from '@/Components/Pagination';

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 TempCredential = {
  studentId: number;
  fullName: string;
  username: string;
  password: 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 }>;
  tempCredentials: TempCredential[];
  pagination: { total: number; perPage: number; currentPage: number; lastPage: number };
  filters: { q: 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, tempCredentials, pagination, filters }: Props) {
  const [editId, setEditId] = useState<number | null>(null);
  const [search, setSearch] = useState(filters.q);
  const [rowClassroom, setRowClassroom] = useState<Record<number, string>>({});
  const printRef = useRef<HTMLDivElement>(null);
  const form = useForm({ ...blank });

  function doSearch(q: string) {
    setSearch(q);
    router.get('/school/students', { q, page: 1 }, { preserveScroll: true, replace: true });
  }

  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 });
  }

  function handleResetTempPassword(tc: TempCredential) {
    if (!confirm(`رمز موقت جدید برای «${tc.fullName}» صادر شود؟`)) return;
    router.post(`/school/students/${tc.studentId}/reset-temp-password`, {}, { preserveScroll: true });
  }

  function selectedClassFor(student: StudentRow): string {
    return rowClassroom[student.id] ?? (student.classroomId ? String(student.classroomId) : '');
  }

  function handleTransfer(student: StudentRow) {
    const toClassroomId = selectedClassFor(student);
    if (!toClassroomId) return;
    if (student.classroomId && Number(toClassroomId) === student.classroomId) {
      alert('کلاس مقصد با کلاس فعلی یکی است.');
      return;
    }
    if (!confirm(`دانش‌آموز «${student.fullName}» به کلاس انتخاب‌شده منتقل شود؟`)) return;
    router.post(`/school/students/${student.id}/transfer`, { to_classroom_id: Number(toClassroomId) }, { preserveScroll: true });
  }

  function handleDeleteStudentHistory(student: StudentRow) {
    const classroomId = selectedClassFor(student);
    if (!classroomId) return;
    if (!confirm(`سوابق نمرات و حضور و غیاب «${student.fullName}» برای این کلاس حذف شود؟ این کار فقط برای مواقع ضروری است.`)) return;
    router.post(`/school/students/${student.id}/delete-history`, { classroom_id: Number(classroomId) }, { preserveScroll: true });
  }

  function handlePrintCredentials() {
    const w = window.open('', '_blank', 'width=900,height=700');
    if (!w || !printRef.current) return;
    w.document.write(`
      <!doctype html><html dir="rtl" lang="fa">
      <head><meta charset="utf-8"><title>رمزهای موقت دانش‌آموزان</title>
      <style>
        body{font-family:Vazirmatn,Tahoma,sans-serif;padding:32px;direction:rtl;}
        h2{margin-bottom:16px;}
        table{width:100%;border-collapse:collapse;}
        th,td{border:1px solid #ccc;padding:8px 12px;text-align:right;}
        th{background:#f3f4f6;font-weight:700;}
        tr:nth-child(even){background:#f9fafb;}
      </style></head>
      <body>
      <h2>لیست رمزهای موقت دانش‌آموزان</h2>
      <p style="color:#888;font-size:12px">این رمزها یکبار مصرف است.</p>
      ${printRef.current.innerHTML}
      </body></html>
    `);
    w.document.close();
    w.focus();
    setTimeout(() => { w.print(); }, 400);
  }

  return (
    <AppLayout title="دانش‌آموزان">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>پرونده دانش‌آموزان</h2>
            <p>مدیریت اطلاعات، وضعیت تکمیل پروفایل، شماره‌های تماس پدر/مادر و آمار آنلاین بودن.</p>
          </div>
          <div className="action-row">
            <input
              type="search"
              className="input-base"
              placeholder="جستجو (نام / کد)..."
              value={search}
              onChange={(e) => doSearch(e.target.value)}
              style={{ minWidth: 200 }}
            />
            <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">
                        <select
                          className="form-select"
                          value={selectedClassFor(student)}
                          onChange={(e) => setRowClassroom((prev) => ({ ...prev, [student.id]: e.target.value }))}
                          style={{ width: 150, fontSize: '0.78rem' }}
                          title="کلاس مقصد / کلاس حذف سوابق"
                        >
                          <option value="">کلاس...</option>
                          {classroomOptions.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
                        </select>
                        <button className="btn btn-ghost btn-sm" type="button" onClick={() => startEdit(student)}>
                          <i className="bi bi-pencil" />
                        </button>
                        <a
                          className="btn btn-ghost btn-sm"
                          href={`/school/students/${student.id}/id-card`}
                          target="_blank"
                          rel="noreferrer"
                          title="کارت دانش‌آموزی PDF"
                        >
                          <i className="bi bi-person-vcard" />
                        </a>
                        <button
                          className="btn btn-ghost btn-sm"
                          type="button"
                          title="انتقال به کلاس دیگر"
                          onClick={() => handleTransfer(student)}
                        >
                          <i className="bi bi-arrow-left-right" />
                        </button>
                        <button
                          className="btn btn-danger-ghost btn-sm"
                          type="button"
                          title="حذف سوابق این کلاس"
                          onClick={() => handleDeleteStudentHistory(student)}
                        >
                          <i className="bi bi-eraser" />
                        </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>
        )}

        <Pagination {...pagination} url="/school/students" extraParams={{ q: filters.q }} />

        {/* Student temp credentials table */}
        <section className="panel-card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div>
              <h2><i className="bi bi-shield-lock" /> رمزهای موقت دانش‌آموزان</h2>
              <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
                برای صدور رمز اولیه دانش‌آموز، از بخش <a href="/school/credentials">مدیریت ورود</a> استفاده کنید.
              </p>
            </div>
            {tempCredentials.length > 0 && (
              <button className="btn btn-soft btn-sm" type="button" onClick={handlePrintCredentials}>
                <i className="bi bi-printer" /> دریافت PDF
              </button>
            )}
          </div>

          {tempCredentials.length > 0 ? (
            <div ref={printRef}>
              <div className="table-wrap">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>نام دانش‌آموز</th>
                      <th>نام کاربری</th>
                      <th>رمز موقت</th>
                      <th>عملیات</th>
                    </tr>
                  </thead>
                  <tbody>
                    {tempCredentials.map((tc) => (
                      <tr key={tc.studentId}>
                        <td>{tc.fullName}</td>
                        <td style={{ fontFamily: 'monospace', direction: 'ltr', textAlign: 'left' }}>{tc.username}</td>
                        <td style={{ fontFamily: 'monospace', direction: 'ltr', textAlign: 'left', fontWeight: 700, letterSpacing: 2 }}>{tc.password}</td>
                        <td>
                          <button
                            className="btn btn-ghost btn-sm"
                            type="button"
                            title="رمز موقت جدید"
                            onClick={() => handleResetTempPassword(tc)}
                          >
                            <i className="bi bi-arrow-repeat" /> رمز جدید
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : (
            <p style={{ color: 'var(--color-text-muted)' }}>
              رمز موقتی وجود ندارد — بعد از صدور کارت ورود دانش‌آموز از بخش مدیریت ورود، اینجا نمایش داده می‌شود.
            </p>
          )}
        </section>
      </div>
    </AppLayout>
  );
}
