"use client";

/**
 * 班级诊断视图（P7-insights）
 *
 * 数据来源：GraphQL ClassDiagnosticQuery
 *
 * 功能：
 * - 顶部：班级基本信息 + 掌握度摘要（5 知识点 avg）
 * - 知识点掌握度列表（10 知识点，每点 avg/中位数/学生数/掌握分布）
 * - 学生掌握度排名表
 * - 监控埋点（mock console.log）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useEffect } from "react";
import { useQuery } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassDiagnosticQuery } from "@/lib/graphql-p7-insights";
import type {
  ClassDiagnostic,
  DiagnosticKpMastery,
} from "@/lib/graphql-p7-insights";

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 ClassDiagnosticPage(): JSX.Element {
  const params = useParams<{ classId: string }>();
  const classId = params?.classId ?? "";

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

  const diag: ClassDiagnostic | undefined = result.data?.classDiagnostic;

  // 监控埋点（mock console.log）
  useEffect(() => {
    if (diag) {
      console.log("[diagnostic-monitor] class-view-loaded", {
        classId,
        className: diag.className,
        studentCount: diag.studentCount,
        kpCount: diag.kpMastery.length,
        timestamp: new Date().toISOString(),
      });
    }
  }, [diag, classId]);

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <Link
          href="/diagnostic"
          className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
        >
          ← 返回诊断报告
        </Link>
        <h1 className="mt-3 text-3xl font-serif text-ink">
          {diag?.className ?? "班级诊断"}
        </h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL ClassDiagnosticQuery · 班级知识点掌握度与学生排名（P7-insights）
        </p>
      </header>

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

      {!classId ? (
        <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>
      ) : !diag ? (
        <Empty title="暂无诊断数据" description="该班级尚未生成诊断报告" />
      ) : (
        <>
          {/* 基本信息 + 摘要 */}
          <section className="mb-8">
            <div className="mb-4 flex items-baseline gap-6">
              <p className="text-sm text-ink-muted">
                学生数 <span className="text-ink font-mono">{diag.studentCount}</span>
              </p>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {diag.summary.map((s) => (
                <div
                  key={s.knowledgePoint}
                  className="p-4 border border-rule rounded-card"
                >
                  <p className="text-tiny uppercase tracking-wide text-ink-muted">
                    {s.knowledgePoint}
                  </p>
                  <p
                    className="mt-2 text-2xl font-serif"
                    style={{ color: masteryColor(s.avg) }}
                  >
                    {s.avg}
                  </p>
                </div>
              ))}
            </div>
          </section>

          {/* 知识点掌握度列表 */}
          <section className="mb-10">
            <h2 className="text-xl font-serif text-ink mb-4">知识点掌握度</h2>
            <div className="rule-thin mb-6" />
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
                  <th className="py-3 pr-4 font-normal">知识点</th>
                  <th className="py-3 pr-4 font-normal">平均掌握度</th>
                  <th className="py-3 pr-4 font-normal">中位数</th>
                  <th className="py-3 pr-4 font-normal">学生数</th>
                  <th className="py-3 pr-4 font-normal">掌握分布</th>
                </tr>
              </thead>
              <tbody>
                {diag.kpMastery.map((kp: DiagnosticKpMastery) => (
                  <tr key={kp.knowledgePoint} className="border-b border-rule">
                    <td className="py-3 pr-4 text-ink">{kp.knowledgePoint}</td>
                    <td className="py-3 pr-4">
                      <div className="flex items-center gap-2">
                        <span
                          className="font-mono"
                          style={{ color: masteryColor(kp.avg) }}
                        >
                          {kp.avg}
                        </span>
                        <div className="w-16 h-1.5 rounded-button bg-subtle overflow-hidden">
                          <div
                            className="h-full rounded-button"
                            style={{
                              width: `${kp.avg}%`,
                              background: masteryColor(kp.avg),
                            }}
                          />
                        </div>
                      </div>
                    </td>
                    <td className="py-3 pr-4 text-ink-muted font-mono">
                      {kp.median}
                    </td>
                    <td className="py-3 pr-4 text-ink-muted font-mono">
                      {kp.studentCount}
                    </td>
                    <td className="py-3 pr-4">
                      <div className="flex items-center gap-2 text-tiny">
                        <span className="text-success">
                          已掌握 {kp.distribution.mastered}
                        </span>
                        <span className="text-warning">
                          部分 {kp.distribution.partial}
                        </span>
                        <span className="text-danger">
                          薄弱 {kp.distribution.weak}
                        </span>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>

          {/* 学生掌握度排名 */}
          <section>
            <h2 className="text-xl font-serif text-ink mb-4">学生掌握度排名</h2>
            <div className="rule-thin mb-6" />
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
                  <th className="py-3 pr-4 font-normal">排名</th>
                  <th className="py-3 pr-4 font-normal">学生</th>
                  <th className="py-3 pr-4 font-normal">掌握度均值</th>
                </tr>
              </thead>
              <tbody>
                {diag.rankings.map((r) => (
                  <tr key={r.studentId} className="border-b border-rule">
                    <td className="py-3 pr-4 font-serif text-ink-muted">
                      {r.rank}
                    </td>
                    <td className="py-3 pr-4">
                      <Link
                        href={`/analytics/${r.studentId}`}
                        className="text-ink hover:text-accent"
                      >
                        {r.studentName}
                      </Link>
                    </td>
                    <td className="py-3 pr-4">
                      <div className="flex items-center gap-2">
                        <span
                          className="font-mono"
                          style={{ color: masteryColor(r.masteryAvg) }}
                        >
                          {r.masteryAvg}
                        </span>
                        <div className="w-24 h-1.5 rounded-button bg-subtle overflow-hidden">
                          <div
                            className="h-full rounded-button"
                            style={{
                              width: `${r.masteryAvg}%`,
                              background: masteryColor(r.masteryAvg),
                            }}
                          />
                        </div>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        </>
      )}
    </div>
  );
}
