"use client";

/**
 * 考试分析仪表盘
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ExamAnalyticsQuery：分数分布/均分/最高/最低/及格率/科目对比/每题正确率/学生排名
 *
 * 5 个 SVG 图表：
 * 1. 分数分布柱图（0-59/60-69/70-79/80-89/90-100）
 * 2. 每题正确率柱图（20 题横向柱图）
 * 3. 知识点掌握度雷达图
 * 4. 班级对比柱图（含显著性）
 * 5. 历次考试趋势折线图
 *
 * 学生排名表 + "导出分析报告" 按钮（CSV）
 *
 * 维护者：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 { ExamAnalyticsQuery } from "@/lib/graphql-p7-exams";
import type {
  ExamAnalytics,
  ExamQuestionAccuracy,
  ExamHistoryTrend,
} from "@/lib/graphql-p7-exams";
import {
  DistributionBarChart,
  ClassComparisonChart,
  KnowledgeRadarChart,
} from "@/app/(app)/grades/analytics/charts";

// ============ 自定义图表（题正确率 + 历次趋势） ============

/** 每题正确率横向柱图 */
function QuestionAccuracyChart({
  data,
}: {
  data: ExamQuestionAccuracy[];
}): React.ReactNode {
  if (data.length === 0) {
    return <p className="text-sm text-ink-muted">暂无题目正确率数据</p>;
  }
  const W = 520;
  const H = 360;
  const PAD = { top: 16, right: 32, bottom: 24, left: 48 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;
  const barH = Math.max(6, innerH / data.length - 2);
  // 正确率 0-100
  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full border border-rule rounded-card bg-surface"
      role="img"
      aria-label="每题正确率横向柱图"
    >
      {/* 网格线 */}
      {[0, 25, 50, 75, 100].map((v) => {
        const x = PAD.left + (v / 100) * innerW;
        return (
          <g key={`grid-${v}`}>
            <line
              x1={x}
              y1={PAD.top}
              x2={x}
              y2={PAD.top + innerH}
              stroke="var(--color-rule)"
              strokeWidth={1}
              strokeDasharray="3 3"
            />
            <text
              x={x}
              y={H - PAD.bottom + 14}
              textAnchor="middle"
              fontSize="11"
              fontFamily="var(--font-family-mono)"
              fill="var(--color-ink-muted)"
            >
              {v}%
            </text>
          </g>
        );
      })}
      {/* 柱子 */}
      {data.map((item, i) => {
        const y = PAD.top + i * (barH + 2);
        const w = (item.correctRate / 100) * innerW;
        return (
          <g key={item.questionId}>
            <text
              x={PAD.left - 4}
              y={y + barH / 2 + 4}
              textAnchor="end"
              fontSize="10"
              fontFamily="var(--font-family-mono)"
              fill="var(--color-ink-muted)"
            >
              {item.order}
            </text>
            <rect
              x={PAD.left}
              y={y}
              width={Math.max(0, w)}
              height={barH}
              fill={
                item.correctRate < 50
                  ? "var(--color-danger)"
                  : item.correctRate < 70
                    ? "var(--color-warning)"
                    : "var(--color-accent)"
              }
              rx={2}
            />
            <text
              x={PAD.left + w + 4}
              y={y + barH / 2 + 4}
              textAnchor="start"
              fontSize="10"
              fontFamily="var(--font-family-mono)"
              fontWeight="600"
              fill="var(--color-ink)"
            >
              {item.correctRate}%
            </text>
          </g>
        );
      })}
    </svg>
  );
}

/** 历次考试趋势折线图 */
function HistoryTrendChart({
  data,
}: {
  data: ExamHistoryTrend[];
}): React.ReactNode {
  if (data.length === 0) {
    return <p className="text-sm text-ink-muted">暂无历次考试趋势</p>;
  }
  const W = 520;
  const H = 200;
  const PAD = { top: 20, right: 24, bottom: 36, left: 36 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;
  const yMax = 100;
  const yMin = 0;
  const yRange = yMax - yMin;
  const xStep = data.length > 1 ? innerW / (data.length - 1) : 0;
  const points = data.map((d, i) => ({
    x: PAD.left + i * xStep,
    y: PAD.top + innerH - ((d.avg - yMin) / yRange) * innerH,
    value: d.avg,
    label: d.examTitle,
  }));
  const linePath = points
    .map((p, i) => `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`)
    .join(" ");
  const firstPoint = points[0];
  const lastPoint = points[points.length - 1];
  if (!firstPoint || !lastPoint) {
    return <p className="text-sm text-ink-muted">暂无历次考试趋势</p>;
  }
  const areaPath = `${linePath} L ${lastPoint.x} ${PAD.top + innerH} L ${firstPoint.x} ${PAD.top + innerH} Z`;
  const gridLines = [0, 50, 100].map((v) => {
    const ratio = 1 - (v - yMin) / yRange;
    return { y: PAD.top + innerH * ratio, value: v };
  });
  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full border border-rule rounded-card bg-surface"
      role="img"
      aria-label="历次考试趋势折线图"
    >
      {gridLines.map((g, i) => (
        <g key={`grid-${i}`}>
          <line
            x1={PAD.left}
            y1={g.y}
            x2={W - PAD.right}
            y2={g.y}
            stroke="var(--color-rule)"
            strokeWidth={1}
            strokeDasharray="3 3"
          />
          <text
            x={PAD.left - 8}
            y={g.y + 4}
            textAnchor="end"
            fontSize="11"
            fontFamily="var(--font-family-mono)"
            fill="var(--color-ink-muted)"
          >
            {g.value}
          </text>
        </g>
      ))}
      <path d={areaPath} fill="var(--color-accent)" fillOpacity={0.08} />
      <path
        d={linePath}
        fill="none"
        stroke="var(--color-accent)"
        strokeWidth={2}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      {points.map((p, i) => (
        <g key={`pt-${i}`}>
          <circle
            cx={p.x}
            cy={p.y}
            r={4}
            fill="var(--color-accent)"
            stroke="var(--bg-paper)"
            strokeWidth={2}
          />
          <text
            x={p.x}
            y={p.y - 10}
            textAnchor="middle"
            fontSize="11"
            fontFamily="var(--font-family-mono)"
            fontWeight="600"
            fill="var(--color-ink)"
          >
            {p.value}
          </text>
          <text
            x={p.x}
            y={H - PAD.bottom + 18}
            textAnchor="middle"
            fontSize="10"
            fontFamily="var(--font-family-sans)"
            fill="var(--color-ink-muted)"
          >
            第{i + 1}次
          </text>
        </g>
      ))}
    </svg>
  );
}

// ============ CSV 导出 ============

/** 触发 CSV 下载 */
function exportAnalyticsCsv(analytics: ExamAnalytics): void {
  const lines: string[] = [];
  lines.push("# 考试分析报告");
  lines.push(`# 考试: ${analytics.examTitle}`);
  lines.push(
    `# 应考 ${analytics.summary.expectedCount}, 实考 ${analytics.summary.attendedCount}, 均分 ${analytics.summary.avgScore}, 最高 ${analytics.summary.maxScore}, 最低 ${analytics.summary.minScore}, 及格率 ${analytics.summary.passRate}%`,
  );
  lines.push("");
  lines.push("排名,学号,姓名,总分,等级");
  analytics.rankings.forEach((r) => {
    lines.push(
      [r.rank, r.studentNo, r.studentName, r.totalScore, r.level].join(","),
    );
  });
  lines.push("");
  lines.push("题号,题目,正确率,平均得分,满分");
  analytics.questionAccuracy.forEach((q) => {
    const title = q.questionTitle.replace(/[\r\n,]/g, " ");
    lines.push(
      [q.order, title, `${q.correctRate}%`, q.avgScore, q.maxScore].join(","),
    );
  });
  const blob = new Blob(["\ufeff" + lines.join("\n")], {
    type: "text/csv;charset=utf-8",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `exam-analytics-${analytics.examId}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

// ============ 页面 ============

export default function ExamAnalyticsPage(): React.ReactNode {
  const params = useParams<{ id: string }>();
  const examId = params?.id ?? "";

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

  const analytics: ExamAnalytics | undefined = result.data?.examAnalytics;

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={examId ? `/exams/${examId}` : "/exams"}
            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 ExamAnalyticsQuery · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {result.fetching ? (
        <Loading lines={8} />
      ) : 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>
      ) : !analytics ? (
        <Empty
          title="未找到分析数据"
          description="该考试暂未生成考后分析，或考试 ID 不存在"
        />
      ) : (
        <section className="space-y-6">
          {/* 顶部统计卡片 */}
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
            {[
              { label: "应考人数", value: `${analytics.summary.expectedCount}` },
              { label: "实考人数", value: `${analytics.summary.attendedCount}` },
              { label: "平均分", value: `${analytics.summary.avgScore}` },
              { label: "最高分", value: `${analytics.summary.maxScore}` },
              { label: "最低分", value: `${analytics.summary.minScore}` },
              { label: "及格率", value: `${analytics.summary.passRate}%` },
            ].map((c) => (
              <div
                key={c.label}
                className="border border-rule rounded-card p-3 bg-surface"
              >
                <p className="text-tiny uppercase tracking-wide text-ink-muted">
                  {c.label}
                </p>
                <p className="mt-1 text-2xl font-mono text-ink">{c.value}</p>
              </div>
            ))}
          </div>

          {/* 导出按钮 */}
          <div className="flex items-center justify-end">
            <button
              type="button"
              onClick={() => exportAnalyticsCsv(analytics)}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
            >
              导出分析报告（CSV）
            </button>
          </div>

          {/* 5 个图表 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <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>

            <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">
                红色 &lt;50% · 黄色 50-70% · 蓝色 &gt;70%
              </p>
              <QuestionAccuracyChart data={analytics.questionAccuracy} />
            </div>

            <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>

            <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">
                最近 {analytics.historyTrend.length} 次考试平均分变化
              </p>
              <HistoryTrendChart data={analytics.historyTrend} />
            </div>

            <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 className="border border-rule rounded-card p-4 bg-surface">
            <h2 className="text-base font-serif text-ink mb-3">
              学生排名
              <span className="ml-2 text-sm font-sans text-ink-muted">
                共 {analytics.rankings.length} 名
              </span>
            </h2>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-rule">
                    <th className="text-left py-2 pr-4 text-tiny uppercase tracking-wide text-ink-muted">
                      排名
                    </th>
                    <th className="text-left py-2 pr-4 text-tiny uppercase tracking-wide text-ink-muted">
                      学号
                    </th>
                    <th className="text-left py-2 pr-4 text-tiny uppercase tracking-wide text-ink-muted">
                      姓名
                    </th>
                    <th className="text-right py-2 pr-4 text-tiny uppercase tracking-wide text-ink-muted">
                      总分
                    </th>
                    <th className="text-right py-2 text-tiny uppercase tracking-wide text-ink-muted">
                      等级
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {analytics.rankings.map((r) => (
                    <tr
                      key={r.studentId}
                      className="border-b border-rule hover:bg-subtle"
                    >
                      <td className="py-2 pr-4 font-mono text-ink-muted">
                        {r.rank}
                      </td>
                      <td className="py-2 pr-4 font-mono text-ink">
                        {r.studentNo}
                      </td>
                      <td className="py-2 pr-4 text-ink">{r.studentName}</td>
                      <td className="py-2 pr-4 text-right font-mono text-ink">
                        {r.totalScore}
                      </td>
                      <td className="py-2 text-right font-mono">
                        <span
                          className={
                            r.level === "A" || r.level === "B"
                              ? "text-success"
                              : r.level === "E"
                                ? "text-danger"
                                : "text-ink"
                          }
                        >
                          {r.level}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </section>
      )}
    </div>
  );
}
