"use client";

/**
 * 班级成绩统计页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL GradeStatsQuery：班级成绩统计（avg/median/max/min/passRate/stdDev/rankings）
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 导出 CSV：Blob + URL.createObjectURL
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import { GradeStatsQuery } from "@/lib/graphql-p7-grades";
import type { GradeStats } from "@/lib/graphql-p7-grades";
import { SUBJECTS } from "@/mocks/fixtures/grades-extended";

/** 等级颜色映射（语义令牌） */
function levelColor(level: string): string {
  switch (level) {
    case "A":
      return "var(--color-success)";
    case "B":
      return "var(--color-accent)";
    case "C":
      return "var(--color-ink)";
    case "D":
      return "var(--color-warning)";
    case "E":
      return "var(--color-danger)";
    default:
      return "var(--color-ink-muted)";
  }
}

export default function GradeStatsPage(): React.ReactNode {
  const [classId, setClassId] = useState("");
  const [subject, setSubject] = useState<string>(SUBJECTS[1] ?? "数学");

  // 班级列表
  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];
  const firstClassId = classes[0]?.id ?? "";

  // classId 为空时回退到第一个班级（用户未选择时）
  const targetClassId = classId || firstClassId;

  const [statsResult] = useQuery({
    query: GradeStatsQuery,
    variables: { classId: targetClassId, subject },
    pause: !targetClassId,
  });

  const stats: GradeStats | undefined = statsResult.data?.gradeStats;

  /** 导出 CSV：排名表 */
  function exportCsv() {
    if (!stats) return;
    const header = "排名,学号,姓名,总分,等级\n";
    const rows = stats.rankings
      .map(
        (r) =>
          `${r.rank},${r.studentNo},${r.studentName},${r.totalScore},${r.level}`,
      )
      .join("\n");
    // BOM 头确保 Excel 正确识别 UTF-8
    const csv = "\uFEFF" + header + rows;
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `成绩统计_${stats.className}_${stats.subject}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <p className="mb-2">
            <Link
              href="/grades"
              className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
            >
              ← 返回成绩查询
            </Link>
          </p>
          <h1 className="text-3xl font-serif text-ink">班级成绩统计</h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL GradeStatsQuery · core-edu 域（P7 扩展，MSW mock）
          </p>
        </div>
        {stats && (
          <button
            type="button"
            onClick={exportCsv}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            导出 CSV
          </button>
        )}
      </header>

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

      {/* 班级 + 学科筛选 */}
      <section className="mb-8">
        <div className="grid grid-cols-2 gap-6">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              班级
            </label>
            <select
              value={targetClassId}
              onChange={(e) => setClassId(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              <option value="">请选择班级</option>
              {classes.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              学科
            </label>
            <select
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              {SUBJECTS.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </div>
        </div>
      </section>

      {classesResult.fetching ? (
        <Loading lines={4} />
      ) : statsResult.fetching ? (
        <Loading lines={6} />
      ) : statsResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{statsResult.error.message}
          </p>
        </div>
      ) : !stats ? (
        <Empty title="暂无统计数据" description="请选择班级和学科" />
      ) : (
        <>
          {/* 5 个统计卡片 */}
          <section className="mb-10">
            <h2 className="text-xl font-serif text-ink mb-4">
              {stats.className} · {stats.subject}
            </h2>
            <div className="rule-thin mb-6" />
            <dl className="grid grid-cols-5 gap-4">
              <div className="p-4 border border-rule rounded-card">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  平均分
                </dt>
                <dd className="mt-2 text-3xl font-serif text-accent">
                  {stats.avg.toFixed(1)}
                </dd>
              </div>
              <div className="p-4 border border-rule rounded-card">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  中位数
                </dt>
                <dd className="mt-2 text-3xl font-serif text-ink">
                  {stats.median.toFixed(1)}
                </dd>
              </div>
              <div className="p-4 border border-rule rounded-card">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  最高分
                </dt>
                <dd className="mt-2 text-3xl font-serif text-success">
                  {stats.max}
                </dd>
              </div>
              <div className="p-4 border border-rule rounded-card">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  最低分
                </dt>
                <dd className="mt-2 text-3xl font-serif text-danger">
                  {stats.min}
                </dd>
              </div>
              <div className="p-4 border border-rule rounded-card">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  及格率
                </dt>
                <dd className="mt-2 text-3xl font-serif text-ink">
                  {stats.passRate.toFixed(1)}%
                </dd>
              </div>
            </dl>
            <p className="mt-4 text-tiny text-ink-muted">
              标准差 σ = {stats.stdDev.toFixed(1)} · 共 {stats.totalCount} 名学生
            </p>
          </section>

          {/* 排名表格 */}
          <section>
            <h2 className="text-xl font-serif text-ink mb-4">学生排名</h2>
            <div className="rule-thin mb-4" />
            <div className="border border-rule rounded-card overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-subtle">
                  <tr>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted w-20">
                      排名
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      学号
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      姓名
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted w-32">
                      总分
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted w-24">
                      等级
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {stats.rankings.map((r) => (
                    <tr key={r.studentId} className="border-t border-rule">
                      <td className="px-4 py-3 font-serif text-ink">
                        {r.rank <= 3 ? (
                          <span className="text-accent">{r.rank}</span>
                        ) : (
                          r.rank
                        )}
                      </td>
                      <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                        {r.studentNo}
                      </td>
                      <td className="px-4 py-3 font-serif text-ink">
                        {r.studentName}
                      </td>
                      <td className="px-4 py-3 font-serif text-lg text-ink">
                        {r.totalScore}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className="inline-block px-2 py-0.5 rounded-button text-tiny font-mono"
                          style={{
                            color: levelColor(r.level),
                            border: `1px solid ${levelColor(r.level)}`,
                          }}
                        >
                          {r.level}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        </>
      )}
    </div>
  );
}
