"use client";

/**
 * Analytics 页面 - 班级学情分析仪表盘
 *
 * 数据来源（P4 扩展，MSW mock）：
 * - GraphQL ClassAnalyticsQuery：班级均分/及格率/趋势/Top 学生/弱项
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 班级选择：URL ?classId=xxx 或下拉选择（同步 URL）
 *
 * 维护者：ai13（teacher-portal）
 */

import { Suspense, useMemo } from "react";
import { useQuery } from "urql";
import { useSearchParams, useRouter } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery, ClassQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import { ClassAnalyticsQuery } from "@/lib/graphql-p4";
import type { ClassAnalytics } from "@/lib/graphql-p4";
import TrendChart from "./TrendChart";

function AnalyticsContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const classId = searchParams.get("classId") ?? "";

  // 班级列表（下拉选项）
  const [classesResult] = useQuery({ query: ClassesQuery });
  // 当前班级详情（显示名称）
  const [classResult] = useQuery({
    query: ClassQuery,
    variables: { id: classId },
    pause: !classId,
  });
  // 班级学情分析
  const [analyticsResult] = useQuery({
    query: ClassAnalyticsQuery,
    variables: { classId },
    pause: !classId,
  });

  const classes: Class[] = classesResult.data?.classes ?? [];
  const cls = classResult.data?.class ?? null;
  const analytics: ClassAnalytics | undefined =
    analyticsResult.data?.classAnalytics;

  // 掌握度 = Top 学生 masteryRate 均值（classAnalytics 无直接字段，从 topStudents 推算）
  const masteryRate = useMemo(() => {
    if (!analytics?.topStudents || analytics.topStudents.length === 0) {
      return 0;
    }
    const sum = analytics.topStudents.reduce(
      (acc, s) => acc + s.masteryRate,
      0,
    );
    return Math.round(sum / analytics.topStudents.length);
  }, [analytics]);

  function selectClass(id: string) {
    const params = new URLSearchParams(searchParams);
    if (id) {
      params.set("classId", id);
    } else {
      params.delete("classId");
    }
    router.push(`/analytics${params.toString() ? `?${params}` : ""}`);
  }

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">学情分析</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL ClassAnalyticsQuery · 班级学情聚合（P4 扩展，MSW mock）
        </p>
      </header>

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

      {/* 班级选择 */}
      <div className="mb-6 flex items-baseline gap-3">
        <label className="text-tiny uppercase tracking-wide text-ink-muted">
          班级
        </label>
        <select
          value={classId}
          onChange={(e) => selectClass(e.target.value)}
          className="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>
        {cls ? (
          <span className="ml-2 text-tiny text-ink-muted">
            {cls.studentCount} 名学生
          </span>
        ) : null}
      </div>

      {!classId ? (
        <Empty
          title="请选择班级"
          description="选择班级后查看学情分析数据"
        />
      ) : analyticsResult.fetching ? (
        <Loading lines={6} />
      ) : 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="该班级尚未生成分析报告" />
      ) : (
        <>
          {/* 概览卡片 */}
          <section className="grid grid-cols-3 gap-6 mb-10">
            <div className="p-6 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                平均分
              </p>
              <p className="mt-3 text-4xl font-serif text-ink">
                {analytics.avgScore.toFixed(1)}
              </p>
            </div>
            <div className="p-6 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                及格率
              </p>
              <p className="mt-3 text-4xl font-serif text-success">
                {analytics.passRate}%
              </p>
            </div>
            <div className="p-6 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                掌握度
              </p>
              <p className="mt-3 text-4xl font-serif text-accent">
                {masteryRate}%
              </p>
            </div>
          </section>

          {/* 成绩趋势图 */}
          <section className="mb-10">
            <h2 className="text-xl font-serif text-ink mb-4">
              班级成绩趋势
            </h2>
            <div className="rule-thin mb-6" />
            <TrendChart data={analytics.avgTrend} labelPrefix="第" />
          </section>

          {/* Top 学生 + 弱项 */}
          <section className="grid grid-cols-3 gap-8">
            {/* Top 5 学生 */}
            <div className="col-span-2">
              <h2 className="text-xl font-serif text-ink mb-4">
                Top 5 学生
              </h2>
              <div className="rule-thin mb-6" />
              <ul className="space-y-0">
                {analytics.topStudents.map((s, i) => (
                  <li
                    key={s.studentId}
                    className="py-4 grid grid-cols-12 gap-4 items-baseline border-b border-rule"
                  >
                    <div className="col-span-1 text-2xl font-serif text-ink-muted">
                      {i + 1}
                    </div>
                    <div className="col-span-4">
                      <Link
                        href={`/analytics/${s.studentId}`}
                        className="text-lg font-serif text-ink hover:text-accent"
                      >
                        {s.studentName}
                      </Link>
                      <p className="mt-1 text-tiny text-ink-muted">
                        {s.strongPoints.length} 项强 · {s.weakPoints.length} 项弱
                      </p>
                    </div>
                    <div className="col-span-3 text-sm text-ink">
                      均分
                      <span className="ml-2 text-lg font-serif text-accent">
                        {s.avgScore}
                      </span>
                    </div>
                    <div className="col-span-3 text-right">
                      <div className="flex items-baseline justify-end gap-2">
                        <span className="text-tiny text-ink-muted">
                          掌握度
                        </span>
                        <span
                          className="text-lg font-serif"
                          style={{
                            color:
                              s.masteryRate >= 70
                                ? "var(--color-success)"
                                : s.masteryRate >= 40
                                  ? "var(--color-warning)"
                                  : "var(--color-danger)",
                          }}
                        >
                          {s.masteryRate}%
                        </span>
                      </div>
                      <div className="mt-1 h-1.5 rounded-button bg-subtle overflow-hidden">
                        <div
                          className="h-full rounded-button"
                          style={{
                            width: `${s.masteryRate}%`,
                            background:
                              s.masteryRate >= 70
                                ? "var(--color-success)"
                                : s.masteryRate >= 40
                                  ? "var(--color-warning)"
                                  : "var(--color-danger)",
                          }}
                        />
                      </div>
                    </div>
                    <div className="col-span-1 text-right">
                      <Link
                        href={`/analytics/${s.studentId}`}
                        className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                      >
                        详情
                      </Link>
                    </div>
                  </li>
                ))}
              </ul>
            </div>

            {/* 班级弱项 */}
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">
                班级弱项
              </h2>
              <div className="rule-thin mb-6" />
              {analytics.weakPoints.length === 0 ? (
                <p className="text-sm text-ink-muted">暂无明显弱项</p>
              ) : (
                <ul className="space-y-2">
                  {analytics.weakPoints.map((wp, i) => (
                    <li
                      key={i}
                      className="flex items-center gap-3 py-2 px-3 border-b border-rule"
                    >
                      <span
                        className="inline-block w-2 h-2 rounded-full"
                        style={{ background: "var(--color-danger)" }}
                      />
                      <span className="text-sm text-ink">{wp}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </section>
        </>
      )}
    </div>
  );
}

export default function AnalyticsPage() {
  return (
    <Suspense
      fallback={
        <div className="px-10 py-10">
          <Loading lines={3} />
        </div>
      }
    >
      <AnalyticsContent />
    </Suspense>
  );
}
