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

type ScoreEntry = { score: number; max: number; note: string | null } | null;

type Student = {
  id: number;
  name: string;
  code: string;
  scores: Record<number, ScoreEntry>;
  avg: number | null;
};

type Subject = {
  id: number;
  name: string;
  classAvg: number | null;
};

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

type Props = {
  classrooms: Classroom[];
  classroomId: number | null;
  term: number | null;
  hasTermFilter: boolean;
  students: Student[];
  subjects: Subject[];
};

function pctColor(score: number, max: number): string {
  const p = max > 0 ? (score / max) * 100 : 0;
  if (p >= 70) return '#16a34a';
  if (p >= 50) return '#d97706';
  return '#dc2626';
}

function avgColor(avg: number | null): string {
  if (avg === null) return 'var(--color-text-muted)';
  if (avg >= 70) return '#16a34a';
  if (avg >= 50) return '#d97706';
  return '#dc2626';
}

export default function ClassGradeSheet({ classrooms, classroomId, term, hasTermFilter, students, subjects }: Props) {
  function changeFilters(next: { classroom_id?: string | number | null; term?: string | number | null }) {
    router.get('/teacher/grade-sheet', {
      classroom_id: next.classroom_id ?? classroomId ?? undefined,
      term: next.term ?? term ?? undefined,
    }, { preserveScroll: false });
  }

  const exportListUrl = classroomId
    ? `/teacher/grades/export?classroom_id=${classroomId}&mode=list${term ? `&term=${term}` : ''}`
    : '/teacher/grades/export?mode=list';

  const exportSheetUrl = classroomId
    ? `/teacher/grades/export?classroom_id=${classroomId}&mode=sheet${term ? `&term=${term}` : ''}`
    : null;

  return (
    <AppLayout title="کارنامه کلاس">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-table" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />کارنامه گروهی کلاس</h2>
            <p>نمرات تایید‌شده همه دانش‌آموزان به تفکیک درس</p>
          </div>
          <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
            <select
              className="form-control"
              style={{ minWidth: 160 }}
              value={classroomId ?? ''}
              onChange={(e) => changeFilters({ classroom_id: e.target.value })}
            >
              <option value="">انتخاب کلاس</option>
              {classrooms.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
            {hasTermFilter && (
              <select
                className="form-control"
                style={{ minWidth: 130 }}
                value={term ?? ''}
                onChange={(e) => changeFilters({ term: e.target.value || null })}
              >
                <option value="">همه ترم‌ها</option>
                <option value="1">ترم ۱</option>
                <option value="2">ترم ۲</option>
                <option value="3">ترم ۳</option>
              </select>
            )}
            <a className="btn btn-soft btn-sm" href={exportListUrl}>
              <i className="bi bi-file-earmark-excel" /> خروجی Excel لیست
            </a>
            {exportSheetUrl && (
              <a className="btn btn-primary btn-sm" href={exportSheetUrl}>
                <i className="bi bi-grid-3x3-gap" /> کارنامه Excel
              </a>
            )}
          </div>
        </section>

        {students.length === 0 || subjects.length === 0 ? (
          <div className="panel-card" style={{ textAlign: 'center', padding: '2.5rem', color: 'var(--color-text-muted)' }}>
            <i className="bi bi-table" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.75rem' }} />
            {classroomId ? 'نمره تایید‌شده‌ای برای این کلاس ثبت نشده' : 'یک کلاس انتخاب کنید'}
          </div>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%', minWidth: 600 }}>
                <thead>
                  <tr>
                    <th style={{ position: 'sticky', right: 0, background: 'var(--color-bg-soft)', zIndex: 1 }}>دانش‌آموز</th>
                    {subjects.map((s) => (
                      <th key={s.id} style={{ whiteSpace: 'nowrap', minWidth: 90 }}>
                        {s.name}
                      </th>
                    ))}
                    <th style={{ background: 'var(--color-primary-soft)' }}>میانگین</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map((stu) => (
                    <tr key={stu.id}>
                      <td style={{ position: 'sticky', right: 0, background: 'var(--color-surface)', fontWeight: 600, whiteSpace: 'nowrap' }}>
                        <a href={`/teacher/students/${stu.id}/detail`} style={{ color: 'inherit', textDecoration: 'none' }}>
                          {stu.name}
                        </a>
                        <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', fontWeight: 400 }}>{stu.code}</div>
                      </td>
                      {subjects.map((s) => {
                        const entry = stu.scores[s.id];
                        return (
                          <td key={s.id} style={{ textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
                            {entry ? (
                              <span
                                style={{ fontWeight: 600, color: pctColor(entry.score, entry.max) }}
                                title={entry.note ?? undefined}
                              >
                                {entry.score}
                                <span style={{ fontWeight: 400, fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>/{entry.max}</span>
                                {entry.note && <i className="bi bi-chat-dots" style={{ fontSize: '0.7rem', marginRight: '0.2rem', color: 'var(--color-info)' }} />}
                              </span>
                            ) : (
                              <span style={{ color: 'var(--color-text-muted)', fontSize: '0.8rem' }}>—</span>
                            )}
                          </td>
                        );
                      })}
                      <td style={{ textAlign: 'center', fontWeight: 700, color: avgColor(stu.avg), background: 'var(--color-primary-soft)' }}>
                        {stu.avg !== null ? `${stu.avg}%` : '—'}
                      </td>
                    </tr>
                  ))}
                  {/* Class avg row */}
                  <tr style={{ background: 'var(--color-bg-soft)', fontWeight: 700 }}>
                    <td style={{ position: 'sticky', right: 0, background: 'var(--color-bg-soft)' }}>میانگین کلاس</td>
                    {subjects.map((s) => (
                      <td key={s.id} style={{ textAlign: 'center', color: avgColor(s.classAvg) }}>
                        {s.classAvg !== null ? `${s.classAvg}%` : '—'}
                      </td>
                    ))}
                    <td />
                  </tr>
                </tbody>
              </table>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
