import { Link, router } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type Classroom = { id: number; name: string };

type Student = {
  id: number;
  /** شماره دفتر کلاسی — assigned server-side, stable across sorting/filtering. */
  rollNumber: number;
  firstName: string;
  lastName: string;
  fatherName: string | null;
  nationalCode: string | null;
  studentCode: string;
  mobile: string | null;
  username: string | null;
  absenceCount: number;
  avgGrade: number | null;
};

type Props = {
  classrooms: Classroom[];
  classroomId: number | null;
  students: Student[];
};

type SortKey = 'firstName' | 'lastName' | 'fatherName' | 'nationalCode' | 'absenceCount' | 'avgGrade';
type SortDir = 'asc' | 'desc';
type Sort = { key: SortKey; dir: SortDir } | null;

const COLUMNS: Array<{ key: SortKey; label: string }> = [
  { key: 'firstName', label: 'نام' },
  { key: 'lastName', label: 'نام خانوادگی' },
  { key: 'fatherName', label: 'نام پدر' },
  { key: 'nationalCode', label: 'کد ملی' },
  { key: 'absenceCount', label: 'غیبت' },
  { key: 'avgGrade', label: 'میانگین نمرات' },
];

export default function StudentRoster({ classrooms, classroomId, students }: Props) {
  const [search, setSearch] = useState('');
  const [sort, setSort] = useState<Sort>(null);

  function changeClass(id: string) {
    router.get('/teacher/students', { classroom_id: id }, { preserveScroll: true });
  }

  // Click cycles: asc -> desc -> off
  function toggleSort(key: SortKey) {
    setSort((current) => {
      if (!current || current.key !== key) return { key, dir: 'asc' };
      if (current.dir === 'asc') return { key, dir: 'desc' };
      return null;
    });
  }

  const visibleStudents = useMemo(() => {
    const term = search.trim().toLowerCase();

    const filtered = term
      ? students.filter((s) =>
          [s.firstName, s.lastName, s.fatherName ?? '', s.nationalCode ?? '', s.studentCode, s.mobile ?? '', s.username ?? '']
            .some((field) => field.toLowerCase().includes(term)),
        )
      : students;

    if (!sort) return filtered;

    const sorted = [...filtered].sort((a, b) => {
      const av = a[sort.key];
      const bv = b[sort.key];

      // Empty values always sink to the bottom regardless of direction
      const aEmpty = av === null || av === '';
      const bEmpty = bv === null || bv === '';
      if (aEmpty && bEmpty) return 0;
      if (aEmpty) return 1;
      if (bEmpty) return -1;

      if (typeof av === 'number' && typeof bv === 'number') return av - bv;
      return String(av).localeCompare(String(bv), 'fa');
    });

    return sort.dir === 'desc' ? sorted.reverse() : sorted;
  }, [students, search, sort]);

  function sortIcon(key: SortKey) {
    if (!sort || sort.key !== key) return 'bi-arrow-down-up';
    return sort.dir === 'asc' ? 'bi-sort-up-alt' : 'bi-sort-down';
  }

  return (
    <AppLayout title="لیست دانش‌آموزان">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-journal-bookmark" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />دفتر کلاسی</h2>
            <p>روی هر دانش‌آموز کلیک کنید تا پرونده کامل او باز شود</p>
          </div>
          <select
            className="form-control"
            style={{ width: 'auto', minWidth: 160 }}
            value={classroomId ?? ''}
            onChange={(e) => changeClass(e.target.value)}
          >
            <option value="">انتخاب کلاس</option>
            {classrooms.map((c) => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
        </section>

        {students.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>
              <i className="bi bi-people" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.75rem' }} />
              <p>{classroomId ? 'دانش‌آموزی در این کلاس ثبت نشده.' : 'یک کلاس انتخاب کنید.'}</p>
            </div>
          </section>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap' }}>
              <div style={{ position: 'relative', flex: '1 1 280px', maxWidth: 420, minWidth: 220 }}>
                <i
                  className="bi bi-search"
                  style={{ position: 'absolute', right: '0.6rem', top: '50%', transform: 'translateY(-50%)', color: 'var(--color-text-muted)', fontSize: '0.8rem', pointerEvents: 'none' }}
                />
                <input
                  type="search"
                  className="form-control"
                  placeholder="جستجوی نام، نام پدر یا کد ملی…"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  style={{ width: '100%', paddingRight: '1.9rem', fontSize: '0.85rem' }}
                />
              </div>

              {sort && (
                <button type="button" className="btn btn-ghost btn-sm" onClick={() => setSort(null)} style={{ whiteSpace: 'nowrap' }}>
                  <i className="bi bi-x-circle" /> حذف مرتب‌سازی
                </button>
              )}

              <span style={{ marginInlineStart: 'auto', fontSize: '0.875rem', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>
                <i className="bi bi-people" style={{ marginLeft: '0.3rem' }} />
                {visibleStudents.length === students.length
                  ? `${students.length} دانش‌آموز`
                  : `${visibleStudents.length} از ${students.length} دانش‌آموز`}
              </span>
            </div>

            <div style={{ overflowX: 'auto' }}>
              <table className="data-table roster-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th title="شماره دفتر کلاسی">#</th>
                    {COLUMNS.map((col) => (
                      <th key={col.key}>
                        <button
                          type="button"
                          onClick={() => toggleSort(col.key)}
                          title="مرتب‌سازی"
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '0.35rem',
                            background: 'none',
                            border: 'none',
                            padding: 0,
                            font: 'inherit',
                            color: sort?.key === col.key ? 'var(--color-primary)' : 'inherit',
                            cursor: 'pointer',
                          }}
                        >
                          {col.label}
                          <i className={`bi ${sortIcon(col.key)}`} style={{ fontSize: '0.7rem', opacity: sort?.key === col.key ? 1 : 0.45 }} />
                        </button>
                      </th>
                    ))}
                    <th />
                  </tr>
                </thead>
                <tbody>
                  {visibleStudents.length === 0 ? (
                    <tr>
                      <td colSpan={COLUMNS.length + 2} style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>
                        <i className="bi bi-search" style={{ fontSize: '1.5rem', display: 'block', marginBottom: '0.5rem' }} />
                        دانش‌آموزی با «{search}» پیدا نشد.
                      </td>
                    </tr>
                  ) : visibleStudents.map((s) => (
                    <tr
                      key={s.id}
                      className="roster-row"
                      onClick={() => router.visit(`/teacher/students/${s.id}/detail`)}
                      style={{ cursor: 'pointer' }}
                    >
                      <td style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem', fontVariantNumeric: 'tabular-nums' }}>
                        {s.rollNumber}
                      </td>
                      <td style={{ fontWeight: 600 }}>{s.firstName}</td>
                      <td style={{ fontWeight: 600 }}>{s.lastName}</td>
                      <td style={{ fontSize: '0.875rem' }}>{s.fatherName || '—'}</td>
                      <td style={{ fontFamily: 'monospace', fontSize: '0.85rem', direction: 'ltr', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                        {s.nationalCode || '—'}
                      </td>
                      <td>
                        <span
                          className={s.absenceCount > 3 ? 'badge badge-danger' : s.absenceCount > 0 ? 'badge badge-warning' : 'badge badge-success'}
                        >
                          {s.absenceCount > 0 ? `${s.absenceCount} جلسه` : 'بدون غیبت'}
                        </span>
                      </td>
                      <td style={{ fontVariantNumeric: 'tabular-nums' }}>
                        {s.avgGrade !== null ? (
                          <span
                            style={{
                              fontWeight: 700,
                              color: s.avgGrade < 10 ? 'var(--color-danger)' : s.avgGrade < 14 ? 'var(--color-warning)' : 'var(--color-success)',
                            }}
                          >
                            {s.avgGrade}
                          </span>
                        ) : (
                          <span style={{ color: 'var(--color-text-muted)' }}>—</span>
                        )}
                      </td>
                      <td>
                        <Link
                          href={`/teacher/students/${s.id}/detail`}
                          className="btn btn-ghost btn-sm"
                          title="پرونده دانش‌آموز"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <i className="bi bi-folder2-open" />
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
