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

type Student = {
  id: number;
  name: string;
  studentCode: string;
  classroomName: string;
  totalSessions: number;
  absenceCount: number;
  excusedCount: number;
  presentCount: number;
  lateCount: number;
  attendancePct: number;
};

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

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

export default function AbsenceReport({ students, classrooms, filters }: Props) {
  const [minAbsences, setMinAbsences] = useState(String(filters.min_absences));
  const [classroomId, setClassroomId] = useState(filters.classroom_id ? String(filters.classroom_id) : '');

  function applyFilters() {
    router.get('/school/absence-report', {
      min_absences: minAbsences || '3',
      ...(classroomId ? { classroom_id: classroomId } : {}),
    }, { preserveState: true, replace: true });
  }

  function pctColor(pct: number): string {
    if (pct >= 80) return 'var(--color-success)';
    if (pct >= 60) return 'var(--color-warning)';
    return 'var(--color-danger)';
  }

  return (
    <AppLayout title="گزارش دانش‌آموزان پرغیبت">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>گزارش دانش‌آموزان پرغیبت</h2>
            <p>دانش‌آموزانی که تعداد غیبت آن‌ها از حد مشخص شده بیشتر است.</p>
          </div>
        </section>

        <section className="panel-card">
          <div className="form-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', marginBottom: '1rem' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '0.4rem', fontWeight: 600, fontSize: '0.9rem' }}>
                حداقل تعداد غیبت
              </label>
              <input
                type="number"
                min={1}
                value={minAbsences}
                onChange={(e) => setMinAbsences(e.target.value)}
                style={{
                  width: '100%', border: '1.5px solid var(--color-border)', borderRadius: 'var(--radius-sm)',
                  padding: '0.55rem 0.8rem', fontSize: '0.95rem',
                }}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.4rem', fontWeight: 600, fontSize: '0.9rem' }}>
                کلاس
              </label>
              <select
                value={classroomId}
                onChange={(e) => setClassroomId(e.target.value)}
                style={{
                  width: '100%', border: '1.5px solid var(--color-border)', borderRadius: 'var(--radius-sm)',
                  padding: '0.55rem 0.8rem', fontSize: '0.95rem', background: 'white',
                }}
              >
                <option value="">همه کلاس‌ها</option>
                {classrooms.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end' }}>
              <button className="btn btn-primary" type="button" onClick={applyFilters}>
                <i className="bi bi-funnel" /> اعمال فیلتر
              </button>
            </div>
          </div>
        </section>

        {students.length === 0 ? (
          <section className="panel-card">
            <p style={{ color: 'var(--color-text-muted)' }}>
              هیچ دانش‌آموزی با {filters.min_absences} یا بیشتر غیبت یافت نشد.
            </p>
          </section>
        ) : (
          <>
            <div style={{ display: 'flex', gap: '1rem', alignItems: 'center', padding: '0 0.25rem' }}>
              <span style={{ fontSize: '0.9rem', color: 'var(--color-text-muted)' }}>
                {students.length} دانش‌آموز یافت شد
              </span>
            </div>
            <div className="table-wrap panel-card" style={{ padding: 0, overflow: 'hidden' }}>
              <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>
                  {students.map((s) => (
                    <tr key={s.id}>
                      <td style={{ fontWeight: 600 }}>{s.name}</td>
                      <td><code style={{ fontSize: '0.8rem' }}>{s.studentCode}</code></td>
                      <td>{s.classroomName}</td>
                      <td style={{ textAlign: 'center' }}>{s.totalSessions}</td>
                      <td style={{ textAlign: 'center' }}>
                        <span className="badge badge-danger">{s.absenceCount}</span>
                      </td>
                      <td style={{ textAlign: 'center' }}>
                        {s.excusedCount > 0
                          ? <span className="badge badge-warning">{s.excusedCount}</span>
                          : <span style={{ color: 'var(--color-text-muted)' }}>—</span>
                        }
                      </td>
                      <td style={{ textAlign: 'center' }}>
                        {s.lateCount > 0
                          ? <span className="badge badge-muted">{s.lateCount}</span>
                          : <span style={{ color: 'var(--color-text-muted)' }}>—</span>
                        }
                      </td>
                      <td style={{ textAlign: 'center' }}>
                        <span style={{ color: pctColor(s.attendancePct), fontWeight: 700 }}>
                          {s.attendancePct}٪
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
      </div>
    </AppLayout>
  );
}
