"use client";

/**
 * 成绩分析仪表盘
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL GradeAnalyticsQuery：趋势/分布/学科对比/班级对比/知识点掌握度
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 5 个 SVG 图表（参考 analytics/TrendChart.tsx 模式）：
 * 1. 趋势折线图（avg/max/min 三线）
 * 2. 分数分布柱图（5 段）
 * 3. 学科对比柱图（6 学科）
 * 4. 班级对比柱图（含显著性 * 标记）
 * 5. 知识点掌握度雷达图（5 轴）
 *
 * 维护者：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 { GradeAnalyticsQuery } from "@/lib/graphql-p7-grades";
import type { GradeAnalytics } from "@/lib/graphql-p7-grades";
import {
  TrendLineChart,
  DistributionBarChart,
  SubjectComparisonChart,
  ClassComparisonChart,
  KnowledgeRadarChart,
} from "./charts";

/** 学期选项 */
const SEMESTERS = [
  { value: "", label: "全部学期" },
  { value: "1", label: "第一学期" },
  { value: "2", label: "第二学期" },
];

/** 考试类型选项 */
const EXAM_TYPES = [
  { value: "", label: "全部考试" },
  { value: "midterm", label: "期中考试" },
  { value: "final", label: "期末考试" },
  { value: "unit", label: "单元测验" },
];

export default function GradeAnalyticsPage(): React.ReactNode {
  const [classId, setClassId] = useState("");
  const [semester, setSemester] = useState("");
  const [examType, setExamType] = useState("");

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

  // classId 为空时回退到第一个班级
  const targetClassId = classId || firstClassId;

  const [analyticsResult] = useQuery({
    query: GradeAnalyticsQuery,
    variables: {
      classId: targetClassId,
      semester: semester || null,
      examType: examType || null,
    },
    pause: !targetClassId,
  });

  const analytics: GradeAnalytics | undefined =
    analyticsResult.data?.gradeAnalytics;

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <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 GradeAnalyticsQuery · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {/* 筛选区 */}
      <section className="mb-8">
        <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={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={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"
            >
              {SEMESTERS.map((s) => (
                <option key={s.value} value={s.value}>
                  {s.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              考试类型
            </label>
            <select
              value={examType}
              onChange={(e) => setExamType(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"
            >
              {EXAM_TYPES.map((t) => (
                <option key={t.value} value={t.value}>
                  {t.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </section>

      {classesResult.fetching ? (
        <Loading lines={4} />
      ) : analyticsResult.fetching ? (
        <Loading lines={8} />
      ) : analyticsResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{analyticsResult.error.message}
          </p>
        </div>
      ) : !analytics ? (
        <Empty title="暂无分析数据" description="请选择班级后查看成绩分析" />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 1. 趋势折线图 */}
          <div className="p-4 border border-rule rounded-card">
            <h2 className="text-base font-serif text-ink mb-3">成绩趋势</h2>
            <p className="text-tiny text-ink-muted mb-3">
              实线为平均分，虚线为最高/最低分
            </p>
            <TrendLineChart data={analytics.trend} />
          </div>

          {/* 2. 分数分布柱图 */}
          <div className="p-4 border border-rule rounded-card">
            <h2 className="text-base font-serif text-ink mb-3">分数段分布</h2>
            <p className="text-tiny text-ink-muted mb-3">
              按五段统计学生人数
            </p>
            <DistributionBarChart data={analytics.distribution} />
          </div>

          {/* 3. 学科对比柱图 */}
          <div className="p-4 border border-rule rounded-card">
            <h2 className="text-base font-serif text-ink mb-3">学科对比</h2>
            <p className="text-tiny text-ink-muted mb-3">
              六大学科平均分对比
            </p>
            <SubjectComparisonChart data={analytics.subjectComparison} />
          </div>

          {/* 4. 班级对比柱图 */}
          <div className="p-4 border border-rule rounded-card">
            <h2 className="text-base font-serif text-ink mb-3">
              班级对比
            </h2>
            <p className="text-tiny text-ink-muted mb-3">
              * 标记表示与其他班级存在显著差异
            </p>
            <ClassComparisonChart data={analytics.classComparison} />
          </div>

          {/* 5. 知识点掌握度雷达图 */}
          <div className="p-4 border border-rule rounded-card lg:col-span-2">
            <h2 className="text-base font-serif text-ink mb-3">
              知识点掌握度
            </h2>
            <p className="text-tiny text-ink-muted mb-3">
              五大知识点掌握度雷达图
            </p>
            <KnowledgeRadarChart data={analytics.knowledgeMastery} />
          </div>
        </div>
      )}
    </div>
  );
}
