"use client";

/**
 * ReportCard — 成绩报告卡（批次 A）
 *
 * 数据源：useMyReportCard
 * 视图：报告卡概览（综合平均分/排名/班级统计）+ 各科目成绩明细
 */

import { useMyReportCard } from "@/lib/graphql/hooks";

export default function ReportCardPage(): JSX.Element {
  const { data, fetching, error, reexecute } = useMyReportCard();

  if (fetching) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-5xl mx-auto">
        <p className="text-sm" style={{ color: "var(--color-ink-muted)" }} aria-live="polite">
          加载中…
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-5xl mx-auto">
        <div role="alert" className="card-paper p-6" style={{ borderColor: "var(--color-danger)" }}>
          <p className="text-sm" style={{ color: "var(--color-danger)" }}>
            报告卡加载失败：{error.message}
          </p>
          <button type="button" onClick={() => reexecute()} className="mt-4 btn-secondary text-xs">
            重新加载
          </button>
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-5xl mx-auto">
        <div className="card-paper p-8 text-center">
          <p className="text-4xl font-serif" style={{ color: "var(--color-ink-subtle)" }} aria-hidden="true">
            ◇
          </p>
          <p className="mt-4 text-base font-serif" style={{ color: "var(--color-ink)" }}>
            暂无报告卡数据
          </p>
          <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
            成绩数据汇总后将自动生成报告卡。
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-5xl mx-auto">
      <header className="mb-6">
        <p className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
          成绩档案
        </p>
        <h1 className="mt-2 text-3xl lg:text-4xl font-serif" style={{ color: "var(--color-ink)" }}>
          成绩报告卡
        </h1>
        <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
          {data.studentName} · {data.className} · {data.academicYearName ?? ""} {data.semester === "1" ? "上学期" : data.semester === "2" ? "下学期" : "全学年"}
        </p>
      </header>

      <div className="rule-thin mb-6" />

      <section className="card-paper p-6 mb-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatBox label="综合平均分" value={data.overallAverage.toFixed(1)} />
          <StatBox label="班级排名" value={`${data.overallRank}/${data.classTotalStudents}`} />
          <StatBox label="及格率" value={`${Math.round(data.overallPassRate * 100)}%`} />
          <StatBox label="优秀率" value={`${Math.round(data.overallExcellentRate * 100)}%`} />
        </div>
        <p className="mt-4 text-xs" style={{ color: "var(--color-ink-muted)" }}>
          班主任：{data.classTeacherName} · 生成时间：{new Date(data.generatedAt).toLocaleString("zh-CN")}
        </p>
      </section>

      <section>
        <h2 className="text-base font-serif mb-4" style={{ color: "var(--color-ink)" }}>
          各科目成绩
        </h2>
        <div className="space-y-4">
          {data.subjects.map((subj) => (
            <article key={subj.subjectId} className="card-paper p-5">
              <div className="flex items-start justify-between gap-4 mb-3">
                <div>
                  <p className="text-sm font-serif" style={{ color: "var(--color-ink)" }}>
                    {subj.subjectName}
                  </p>
                  <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
                    平均分 {subj.averageScore.toFixed(1)} · 班级排名 {subj.rankInSubject}/{subj.totalStudentsInSubject}
                  </p>
                </div>
                <span className="text-sm font-serif" style={{ color: "var(--color-ink)" }}>
                  总分 {subj.fullScoreTotal.toFixed(1)}
                </span>
              </div>
              {subj.records.length > 0 && (
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b" style={{ borderColor: "var(--color-rule)" }}>
                      <th className="text-left py-2 text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
                        考试
                      </th>
                      <th className="text-right py-2 text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
                        得分
                      </th>
                      <th className="text-center py-2 text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
                        等级
                      </th>
                      <th className="text-right py-2 text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
                        名次
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {subj.records.map((r) => (
                      <tr key={r.id} className="border-b last:border-b-0" style={{ borderColor: "var(--color-rule)" }}>
                        <td className="py-2" style={{ color: "var(--color-ink)" }}>
                          {r.examName}
                        </td>
                        <td className="text-right py-2 font-serif" style={{ color: "var(--color-ink)" }}>
                          {r.score}
                          <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
                            {" "}/ {r.maxScore}
                          </span>
                        </td>
                        <td className="text-center py-2">
                          <span className={`badge ${getBadgeClassForGrade(r.grade)}`}>
                            {r.grade}
                          </span>
                        </td>
                        <td className="text-right py-2 text-xs" style={{ color: "var(--color-ink-muted)" }}>
                          第 {r.rank} 名
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

function StatBox({ label, value }: { label: string; value: string }): JSX.Element {
  return (
    <div>
      <p className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
        {label}
      </p>
      <p className="mt-1 text-2xl font-serif" style={{ color: "var(--color-ink)" }}>
        {value}
      </p>
    </div>
  );
}

function getBadgeClassForGrade(grade: string): string {
  if (grade === "优秀") return "badge-success";
  if (grade === "良好") return "badge-info";
  if (grade === "及格") return "badge-warning";
  if (grade === "不及格") return "badge-danger";
  return "badge-info";
}
