import { useMemo, useState } from 'react';
import { router, usePage } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { PageHeader } from '@/Components/UI/PageHeader';
import { roleLabel } from '@/lib/roles';

type UserRow = {
  id: number;
  username: string;
  fullName: string;
  role: string;
  hasLoggedIn: boolean;
};

type StudentRow = {
  id: number;
  fullName: string;
  studentCode: string;
  nationalCode: string;
  classroom: string;
};

type Props = {
  users: UserRow[];
  studentsWithoutAccount: StudentRow[];
};

export default function Credentials({ users, studentsWithoutAccount }: Props) {
  const { errors } = usePage().props as { errors: Record<string, string> };
  const [selectedUsers, setSelectedUsers] = useState<Set<number>>(new Set());
  const [selectedStudents, setSelectedStudents] = useState<Set<number>>(new Set());
  const [query, setQuery] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const filteredUsers = useMemo(
    () => users.filter((u) => (u.fullName + u.username).includes(query)),
    [users, query],
  );
  const filteredStudents = useMemo(
    () => studentsWithoutAccount.filter((s) => (s.fullName + s.studentCode + s.nationalCode + s.classroom).includes(query)),
    [studentsWithoutAccount, query],
  );

  const toggle = (set: Set<number>, id: number, setter: (s: Set<number>) => void) => {
    const next = new Set(set);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setter(next);
  };

  const toggleAll = (rows: { id: number }[], set: Set<number>, setter: (s: Set<number>) => void) => {
    const allSelected = rows.every((r) => set.has(r.id));
    const next = new Set(set);
    rows.forEach((r) => (allSelected ? next.delete(r.id) : next.add(r.id)));
    setter(next);
  };

  const total = selectedUsers.size + selectedStudents.size;

  const generate = () => {
    if (total === 0) return;
    if (selectedUsers.size > 0 && !confirm(`رمز عبور ${selectedUsers.size} کاربر موجود عوض می‌شود و رمز قبلی از کار می‌افتد. ادامه؟`)) return;
    setSubmitting(true);
    router.post('/school/credentials/generate', {
      user_ids: [...selectedUsers],
      student_ids: [...selectedStudents],
    }, {
      onFinish: () => setSubmitting(false),
    });
  };

  return (
    <AppLayout title="چاپ کارت ورود">
      <div className="page-stack">
        <PageHeader
          title="چاپ کارت ورود کاربران"
          icon="bi-printer"
          description="کاربران را انتخاب کنید؛ برای هر نفر رمز اولیه جدید ساخته می‌شود و کارت‌های آماده چاپ نمایش داده می‌شوند. نام کاربری دانش‌آموزِ بدون حساب = کد ملی."
        />

        {(errors.user_ids || errors.student_ids) && (
          <div className="panel-card" style={{ borderColor: 'var(--color-danger)' }}>
            <p style={{ color: 'var(--color-danger)', margin: 0 }}>{errors.user_ids ?? errors.student_ids}</p>
          </div>
        )}

        <section className="section-header">
          <input
            style={{
              background: 'var(--color-surface)', border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)', color: 'var(--color-text)',
              font: 'inherit', minHeight: 42, padding: '0.4rem 0.8rem', width: 280,
            }}
            placeholder="جستجو نام، نام کاربری، کد..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <button className="btn btn-primary" type="button" disabled={total === 0 || submitting} onClick={generate}>
            <i className="bi bi-printer" /> صدور و چاپ {total > 0 ? `(${total})` : ''}
          </button>
        </section>

        {studentsWithoutAccount.length > 0 && (
          <section className="panel-card">
            <h2 style={{ marginTop: 0 }}>
              <i className="bi bi-person-plus" style={{ marginLeft: '0.4rem' }} />
              دانش‌آموزان بدون حساب کاربری ({filteredStudents.length})
            </h2>
            <p style={{ color: 'var(--color-text-soft)' }}>برای این‌ها حساب ساخته می‌شود — نام کاربری = کد ملی (اگر نبود، کد دانش‌آموزی).</p>
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th style={{ width: 40 }}>
                      <input
                        type="checkbox"
                        checked={filteredStudents.length > 0 && filteredStudents.every((s) => selectedStudents.has(s.id))}
                        onChange={() => toggleAll(filteredStudents, selectedStudents, setSelectedStudents)}
                      />
                    </th>
                    <th>نام</th>
                    <th>کلاس</th>
                    <th>کد دانش‌آموزی</th>
                    <th>کد ملی</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredStudents.map((s) => (
                    <tr key={s.id}>
                      <td>
                        <input
                          type="checkbox"
                          checked={selectedStudents.has(s.id)}
                          onChange={() => toggle(selectedStudents, s.id, setSelectedStudents)}
                        />
                      </td>
                      <td>{s.fullName}</td>
                      <td>{s.classroom}</td>
                      <td style={{ direction: 'ltr' }}>{s.studentCode}</td>
                      <td style={{ direction: 'ltr' }}>{s.nationalCode || '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}

        <section className="panel-card">
          <h2 style={{ marginTop: 0 }}>
            <i className="bi bi-people" style={{ marginLeft: '0.4rem' }} />
            کاربران موجود ({filteredUsers.length})
          </h2>
          <p style={{ color: 'var(--color-text-soft)' }}>انتخاب یعنی ساخت رمز اولیه جدید — رمز فعلی کاربر باطل می‌شود.</p>
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th style={{ width: 40 }}>
                    <input
                      type="checkbox"
                      checked={filteredUsers.length > 0 && filteredUsers.every((u) => selectedUsers.has(u.id))}
                      onChange={() => toggleAll(filteredUsers, selectedUsers, setSelectedUsers)}
                    />
                  </th>
                  <th>نام</th>
                  <th>نام کاربری</th>
                  <th>نقش</th>
                  <th>وضعیت ورود</th>
                </tr>
              </thead>
              <tbody>
                {filteredUsers.map((u) => (
                  <tr key={u.id}>
                    <td>
                      <input
                        type="checkbox"
                        checked={selectedUsers.has(u.id)}
                        onChange={() => toggle(selectedUsers, u.id, setSelectedUsers)}
                      />
                    </td>
                    <td>{u.fullName}</td>
                    <td style={{ direction: 'ltr' }}>{u.username}</td>
                    <td>{roleLabel(u.role)}</td>
                    <td>
                      {u.hasLoggedIn
                        ? <span className="badge badge-success">وارد شده</span>
                        : <span className="badge badge-muted">هنوز وارد نشده</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </AppLayout>
  );
}
