"use client";

/**
 * 学生成绩报告卡
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ReportCardQuery：学生成绩报告卡（学年/学期/科目成绩 + 排名）
 *
 * 打印：window.print()
 * A4 纸质风格：bg-paper/text-ink 字体
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ReportCardQuery } from "@/lib/graphql-p7-grades";
import type { ReportCard } from "@/lib/graphql-p7-grades";
import {
  REPORT_CARD_STUDENTS,
  REPORT_CARD_SEMESTERS,
} from "@/mocks/fixtures/grades-extended";

export default function ReportCardPage(): React.ReactNode {
  const [studentId, setStudentId] = useState<string>(
    REPORT_CARD_STUDENTS[0]?.id ?? "",
  );
  const [academicYear, setAcademicYear] = useState<string>("");
  const [semester, setSemester] = useState<string>("");

  // 学年选项（从 SEMESTERS 去重）
  const yearOptions = Array.from(
    new Set(REPORT_CARD_SEMESTERS.map((s) => s.year)),
  );

  const [result] = useQuery({
    query: ReportCardQuery,
    variables: {
      studentId,
      academicYear: academicYear || null,
      semester: semester || null,
    },
    pause: !studentId,
  });

  const card: ReportCard | undefined = result.data?.reportCard;

  /** 触发浏览器打印 */
  function handlePrint() {
    window.print();
  }

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between print:hidden">
        <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 ReportCardQuery · core-edu 域（P7 扩展，MSW mock）
          </p>
        </div>
        {card && (
          <button
            type="button"
            onClick={handlePrint}
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
          >
            打印
          </button>
        )}
      </header>

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

      {/* 筛选区 */}
      <section className="mb-8 print:hidden">
        <div className="grid grid-cols-3 gap-6">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              学生
            </label>
            <select
              value={studentId}
              onChange={(e) => setStudentId(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"
            >
              {REPORT_CARD_STUDENTS.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}（{s.no}）
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              学年
            </label>
            <select
              value={academicYear}
              onChange={(e) => setAcademicYear(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>
              {yearOptions.map((y) => (
                <option key={y} value={y}>
                  {y}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              学期
            </label>
            <select
              value={semester}
              onChange={(e) => setSemester(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>
              <option value="1">第一学期</option>
              <option value="2">第二学期</option>
            </select>
          </div>
        </div>
      </section>

      {result.fetching ? (
        <Loading lines={6} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : !card ? (
        <Empty title="暂无报告卡" description="该学生未找到报告卡数据" />
      ) : (
        // A4 纸质风格报告卡
        <article className="max-w-3xl mx-auto bg-paper border border-rule rounded-card p-10 shadow-sm">
          {/* 报告头 */}
          <header className="text-center mb-8 pb-6 border-b-2 border-accent">
            <h1 className="text-2xl font-serif text-ink">
              {card.className} · 成绩报告卡
            </h1>
            <p className="mt-2 text-tiny font-mono text-ink-muted">
              {card.academicYear} 学年第 {card.semester} 学期
            </p>
          </header>

          {/* 学生信息 */}
          <section className="mb-8">
            <dl className="grid grid-cols-3 gap-4 text-sm">
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  姓名
                </dt>
                <dd className="mt-1 font-serif text-ink text-lg">
                  {card.studentName}
                </dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  学号
                </dt>
                <dd className="mt-1 font-mono text-ink">{card.studentNo}</dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  班级
                </dt>
                <dd className="mt-1 font-serif text-ink">{card.className}</dd>
              </div>
            </dl>
          </section>

          {/* 学科成绩表格 */}
          <section className="mb-8">
            <table className="w-full text-sm border border-rule">
              <thead className="bg-subtle">
                <tr>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
                    学科
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule w-24">
                    成绩
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule w-24">
                    班级排名
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
                    任课教师
                  </th>
                </tr>
              </thead>
              <tbody>
                {card.subjects.map((s) => (
                  <tr key={s.subject} className="border-b border-rule">
                    <td className="px-4 py-3 font-serif text-ink">
                      {s.subject}
                    </td>
                    <td className="px-4 py-3 font-serif text-lg text-accent">
                      {s.score}
                    </td>
                    <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                      第 {s.rank} 名
                    </td>
                    <td className="px-4 py-3 font-sans text-sm text-ink">
                      {s.teacherName}
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-subtle">
                  <td className="px-4 py-3 font-serif text-ink">总分</td>
                  <td className="px-4 py-3 font-serif text-xl text-accent">
                    {card.totalScore}
                  </td>
                  <td className="px-4 py-3" colSpan={2} />
                </tr>
              </tfoot>
            </table>
          </section>

          {/* 排名信息 */}
          <section className="mb-8 grid grid-cols-2 gap-6">
            <div className="p-4 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                班级排名
              </p>
              <p className="mt-2 text-2xl font-serif text-accent">
                {card.classRank}
                <span className="ml-1 text-sm font-sans text-ink-muted">
                  / {card.classSize}
                </span>
              </p>
            </div>
            <div className="p-4 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                年级排名
              </p>
              <p className="mt-2 text-2xl font-serif text-ink">
                {card.gradeRank}
                <span className="ml-1 text-sm font-sans text-ink-muted">
                  / {card.gradeSize}
                </span>
              </p>
            </div>
          </section>

          {/* 班主任评语 */}
          <section className="mb-6">
            <h2 className="text-base font-serif text-ink mb-3">班主任评语</h2>
            <div className="rule-thin mb-4" />
            <p className="text-sm leading-relaxed text-ink p-4 bg-subtle rounded-card font-sans">
              {card.teacherComment}
            </p>
          </section>

          {/* 签名区 */}
          <footer className="mt-10 pt-6 border-t border-rule flex justify-between text-sm text-ink-muted font-sans">
            <span>班主任签字：________________</span>
            <span>日期：{new Date().toLocaleDateString("zh-CN")}</span>
          </footer>
        </article>
      )}
    </div>
  );
}
