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

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

type FailingSubject = { subject: string; avg: number; maxScore: number };

type Student = {
  studentId: number;
  name: string;
  studentCode: string;
  overallAvg: number;
  failingSubjects: FailingSubject[];
  failingCount: number;
};

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

export default function AtRisk({ students, classrooms, classroomId, total }: Props) {
  const [expanded, setExpanded] = useState<number | null>(null);

  function changeClass(id: string) {
    router.get('/school/students/at-risk', id ? { classroom_id: id } : {}, { preserveScroll: true });
  }

  return (
    <AppLayout title="دانش‌آموزان در معرض خطر">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-exclamation-triangle" style={{ marginLeft: '0.5rem', color: 'var(--color-danger)' }} />
              دانش‌آموزان در معرض خطر
            </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>

        {total > 0 && (
          <div className="panel-card" style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid var(--color-danger)', padding: '1rem 1.25rem' }}>
            <span style={{ fontWeight: 600, color: 'var(--color-danger)' }}>
              <i className="bi bi-exclamation-triangle-fill" style={{ marginLeft: '0.4rem' }} />
              {total} دانش‌آموز نیاز به پیگیری دارند
            </span>
          </div>
        )}

        {students.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>
              <i className="bi bi-check-circle" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.75rem', color: 'var(--color-success)' }} />
              <h3>همه دانش‌آموزان در وضعیت مطلوب هستند</h3>
              <p>هیچ دانش‌آموزی با میانگین نمره پایین‌تر از حد قبولی یافت نشد.</p>
            </div>
          </section>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th>#</th>
                    <th>نام دانش‌آموز</th>
                    <th>کد دانش‌آموزی</th>
                    <th>میانگین کل</th>
                    <th>درس‌های مشکل‌دار</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {students.map((s, i) => (
                    <>
                      <tr key={s.studentId} style={{ cursor: 'pointer' }} onClick={() => setExpanded(expanded === s.studentId ? null : s.studentId)}>
                        <td style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>{i + 1}</td>
                        <td style={{ fontWeight: 600 }}>{s.name}</td>
                        <td style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{s.studentCode}</td>
                        <td>
                          <span style={{ fontWeight: 700, color: s.overallAvg < 10 ? 'var(--color-danger)' : 'var(--color-warning)' }}>
                            {s.overallAvg}
                          </span>
                        </td>
                        <td>
                          <span className="badge badge-danger">{s.failingCount} درس</span>
                        </td>
                        <td>
                          <i className={`bi bi-chevron-${expanded === s.studentId ? 'up' : 'down'}`} style={{ color: 'var(--color-text-muted)' }} />
                        </td>
                      </tr>
                      {expanded === s.studentId && (
                        <tr key={`${s.studentId}-detail`}>
                          <td colSpan={6} style={{ background: 'var(--color-bg-soft)', padding: '0.75rem 1rem' }}>
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
                              {s.failingSubjects.map((sub, j) => (
                                <div
                                  key={j}
                                  style={{
                                    background: 'white',
                                    border: '1px solid var(--color-danger)',
                                    borderRadius: 'var(--radius-sm)',
                                    padding: '0.3rem 0.8rem',
                                    fontSize: '0.875rem',
                                  }}
                                >
                                  <strong>{sub.subject}</strong>
                                  <span style={{ color: 'var(--color-danger)', marginRight: '0.5rem', fontWeight: 700 }}>
                                    {sub.avg} / {sub.maxScore}
                                  </span>
                                </div>
                              ))}
                            </div>
                            <div style={{ marginTop: '0.5rem' }}>
                              <a href={`/teacher/students/${s.studentId}/scores`} className="btn btn-ghost btn-sm">
                                <i className="bi bi-bar-chart" /> مشاهده کارنامه
                              </a>
                            </div>
                          </td>
                        </tr>
                      )}
                    </>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
