// 成绩页面
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/grades

"use client";

import { useChildGrades } from "@/hooks/useChildGrades";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { ChildGradeChart } from "@/components/ChildGradeChart";
import { formatDate, scoreToGrade, gradeToChinese, cn } from "@/lib/utils";

export default function GradesPage() {
  const { currentChild } = useChildSwitcher();
  const { grades, loading, error } = useChildGrades();

  if (loading) {
    return (
      <div className="space-y-4">
        <span className="skeleton h-8 w-48 rounded" />
        <span className="skeleton h-72 w-full rounded" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded border border-danger p-4 text-sm text-danger">
        加载失败：{error.message}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="font-serif text-2xl">{currentChild?.name}的成绩</h1>

      {grades.length > 0 && <ChildGradeChart grades={grades} />}

      <div className="rounded border border-rule bg-paper-elevated p-4">
        <h3 className="font-serif text-base">成绩明细</h3>
        <table className="mt-3 w-full text-sm">
          <thead>
            <tr className="border-b border-rule text-left text-xs text-ink-muted">
              <th className="pb-2">科目</th>
              <th className="pb-2">考试</th>
              <th className="pb-2">日期</th>
              <th className="pb-2 text-right">分数</th>
              <th className="pb-2 text-right">班均</th>
              <th className="pb-2 text-right">等级</th>
            </tr>
          </thead>
          <tbody>
            {grades.map((g) => {
              const grade = scoreToGrade(g.studentScore, g.classMax ?? 100);
              return (
                <tr
                  key={g.examId}
                  className="border-b border-rule last:border-b-0"
                >
                  <td className="py-2 font-medium">{g.subject}</td>
                  <td className="py-2 text-ink-muted">{g.examName}</td>
                  <td className="py-2 text-ink-muted">
                    {formatDate(g.examDate)}
                  </td>
                  <td className="py-2 text-right font-mono">
                    {g.studentScore}
                  </td>
                  <td className="py-2 text-right font-mono text-ink-muted">
                    {g.classAverage ?? "-"}
                  </td>
                  <td
                    className={cn("py-2 text-right font-medium")}
                    title={gradeToChinese(grade)}
                  >
                    {grade}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
