"use client";

/**
 * StudentAnalytics 详情页 - 单生学情分析
 *
 * 数据来源（P4 扩展，MSW mock）：GraphQL StudentAnalyticsQuery
 * - 成绩趋势图（纯 SVG 折线图）
 * - 弱项 / 强项知识点列表
 * - 掌握度进度条
 *
 * 维护者：ai13（teacher-portal）
 */

import { useQuery } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { StudentAnalyticsQuery } from "@/lib/graphql-p4";
import type { StudentAnalytics } from "@/lib/graphql-p4";
import TrendChart from "../TrendChart";

/** 按掌握度映射语义色（与知识图谱保持一致） */
function masteryColor(rate: number): string {
  if (rate >= 70) return "var(--color-success)";
  if (rate >= 40) return "var(--color-warning)";
  return "var(--color-danger)";
}

export default function StudentAnalyticsPage() {
  const params = useParams<{ studentId: string }>();
  const studentId = params?.studentId ?? "";

  const [result] = useQuery({
    query: StudentAnalyticsQuery,
    variables: { studentId },
    pause: !studentId,
  });

  const student: StudentAnalytics | undefined =
    result.data?.studentAnalytics;

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <Link
          href="/analytics"
          className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
        >
          ← 返回学情分析
        </Link>
        <h1 className="mt-3 text-3xl font-serif text-ink">
          {student ? student.studentName : "学生详情"}
        </h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL StudentAnalyticsQuery · 单生学情（P4 扩展，MSW mock）
        </p>
      </header>

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

      {!studentId ? (
        <Empty title="未指定学生" description="请从学情分析进入查看学生详情" />
      ) : 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>
      ) : !student ? (
        <Empty title="暂无数据" description="该学生尚未生成学情分析" />
      ) : (
        <>
          {/* 概览卡片 */}
          <section className="grid grid-cols-2 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">
                {student.avgScore}
              </p>
            </div>
            <div className="p-6 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                掌握度
              </p>
              <div className="mt-3 flex items-baseline gap-3">
                <span
                  className="text-4xl font-serif"
                  style={{ color: masteryColor(student.masteryRate) }}
                >
                  {student.masteryRate}%
                </span>
              </div>
              <div className="mt-3 h-2 rounded-button bg-subtle overflow-hidden">
                <div
                  className="h-full rounded-button"
                  style={{
                    width: `${student.masteryRate}%`,
                    background: masteryColor(student.masteryRate),
                  }}
                />
              </div>
            </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={student.trend} labelPrefix="第" />
          </section>

          {/* 强项 + 弱项 */}
          <section className="grid grid-cols-2 gap-8">
            {/* 强项 */}
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">强项知识点</h2>
              <div className="rule-thin mb-6" />
              {student.strongPoints.length === 0 ? (
                <p className="text-sm text-ink-muted">暂无明显强项</p>
              ) : (
                <ul className="space-y-2">
                  {student.strongPoints.map((sp, 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-success)" }}
                      />
                      <span className="text-sm text-ink">{sp}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            {/* 弱项 */}
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">弱项知识点</h2>
              <div className="rule-thin mb-6" />
              {student.weakPoints.length === 0 ? (
                <p className="text-sm text-ink-muted">暂无明显弱项</p>
              ) : (
                <ul className="space-y-2">
                  {student.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>
  );
}
