import { useRef, 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;
  nationalCode: string;
  specialty: string;
  mobile: string;
  email: string;
  username: string;
  hasAccount: boolean;
  classes: string;
  subjectIds: number[];
  subjectNames: string;
  status: string;
};

type SubjectOption = { value: number; label: string };

type TempCredential = {
  teacherId: number;
  fullName: string;
  username: string;
  password: string;
};

type Props = {
  teachers: Teacher[];
  subjectOptions: SubjectOption[];
  tempCredentials: TempCredential[];
};

const blank = {
  teacher_code: '',
  national_code: '',
  first_name: '',
  last_name: '',
  mobile: '',
  email: '',
  specialty: '',
  subject_ids: [] as number[],
};

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

  function toggleSubject(subjectId: number) {
    const current = form.data.subject_ids as number[];
    const next = current.includes(subjectId)
      ? current.filter((id) => id !== subjectId)
      : [...current, subjectId];
    form.setData('subject_ids', next);
  }

  function startEdit(teacher: Teacher) {
    setEditId(teacher.id);
    form.setData({
      teacher_code: teacher.teacherCode,
      national_code: teacher.nationalCode,
      first_name: teacher.firstName,
      last_name: teacher.lastName,
      mobile: teacher.mobile,
      email: teacher.email,
      specialty: teacher.specialty,
      subject_ids: teacher.subjectIds,
    });
    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 });
  }

  function handleResetPassword(teacher: Teacher) {
    if (!confirm(`رمز موقت جدید برای «${teacher.fullName}» صادر شود؟`)) return;
    router.post(`/school/teachers/${teacher.id}/reset-password`, {}, { 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;}
        @media print{body{padding:0;}}
      </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>
        </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.national_code} onChange={(e) => form.setData('national_code', e.target.value)} error={form.errors.national_code} placeholder="نام کاربری سیستم = کد ملی" />
            <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>

          {subjectOptions.length > 0 && (
            <div style={{ marginTop: 16 }}>
              <label className="field-label">تخصیص درس به معلم</label>
              <p className="field-hint" style={{ marginBottom: 8 }}>درس‌هایی که این معلم تدریس می‌کند را انتخاب کنید:</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {subjectOptions.map((subject) => {
                  const selected = (form.data.subject_ids as number[]).includes(subject.value);
                  return (
                    <button
                      key={subject.value}
                      type="button"
                      onClick={() => toggleSubject(subject.value)}
                      className={`btn btn-sm ${selected ? 'btn-primary' : 'btn-ghost'}`}
                      style={{ borderRadius: 20 }}
                    >
                      {selected && <i className="bi bi-check2" />} {subject.label}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {!editId && (
            <div className="help-tip" style={{ marginTop: 12 }}>
              <i className="bi bi-info-circle" /> نام کاربری = کد ملی (یا کد پرسنلی اگر کد ملی وارد نشده باشد). رمز موقت بعد از ثبت در جدول زیر نمایش داده می‌شود.
            </div>
          )}

          <div className="action-row" style={{ marginTop: 16 }}>
            <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>
                  <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.nationalCode || '—'}</td>
                    <td>{teacher.subjectNames}</td>
                    <td>{teacher.classes}</td>
                    <td>{teacher.mobile || '—'}</td>
                    <td>
                      {teacher.hasAccount
                        ? <span className="badge badge-success"><i className="bi bi-person-check" /> {teacher.username}</span>
                        : <span className="badge badge-muted">بدون حساب</span>}
                    </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)} title="ویرایش">
                          <i className="bi bi-pencil" />
                        </button>
                        {teacher.hasAccount && (
                          <button className="btn btn-ghost btn-sm" type="button" onClick={() => handleResetPassword(teacher)} title="رمز موقت جدید">
                            <i className="bi bi-key" />
                          </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>از فرم بالا اولین معلم را اضافه کنید.</p>
          </section>
        )}

        {/* 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' }}>
                این رمزها یکبار مصرف است — بعد از اولین ورود معلم، از این لیست حذف می‌شود.
              </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>
                    </tr>
                  </thead>
                  <tbody>
                    {tempCredentials.map((tc) => (
                      <tr key={tc.teacherId}>
                        <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>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : (
            <p style={{ color: 'var(--color-text-muted)' }}>
              رمز موقتی وجود ندارد — بعد از ثبت معلم یا ریست رمز، اینجا نمایش داده می‌شود.
            </p>
          )}
        </section>
      </div>
    </AppLayout>
  );
}
