"use client";

/**
 * 错题分析页（P7-insights）
 *
 * 数据来源：GraphQL ErrorBookQuery
 *
 * 7 个 Widget：
 * 1. 学科 Tab + 班级筛选
 * 2. 5 项统计卡片（错题总数/高频错题/薄弱知识点/平均错误率/上升趋势）
 * 3. 班级对比柱图（5 班级 × 错题数）- 纯 SVG
 * 4. 章节薄弱度横向柱图（10 章节 × 错题数）- 纯 SVG
 * 5. 知识点薄弱度雷达图（10 知识点）- 纯 SVG
 * 6. 学生错题分组表（前 5 学生错题数）
 * 7. Top10 高频错题列表（题干前 100 字/错误率/学科）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import { Loading, Empty } from "@edu/ui-components";
import { ErrorBookQuery } from "@/lib/graphql-p7-insights";
import type {
  ErrorBook as ErrorBookType,
  ErrorBookClassComparison,
  ErrorBookChapterWeakness,
  ErrorBookKpWeakness,
} from "@/lib/graphql-p7-insights";

const SUBJECTS = ["语文", "数学", "英语", "物理", "化学"] as const;

const CLASSES = [
  { id: "", name: "全部班级" },
  { id: "550e8400-e29b-41d4-a716-446655440010", name: "高三(1)班" },
  { id: "550e8400-e29b-41d4-a716-446655440011", name: "高三(2)班" },
  { id: "550e8400-e29b-41d4-a716-446655440012", name: "高三(3)班" },
  { id: "550e8400-e29b-41d4-a716-446655440013", name: "高三(4)班" },
  { id: "550e8400-e29b-41d4-a716-446655440014", name: "高三(5)班" },
];

/** 班级对比柱图（垂直柱） */
function ClassComparisonChart({
  data,
}: {
  data: ErrorBookClassComparison[];
}): React.ReactNode {
  const W = 540;
  const H = 200;
  const PAD = { top: 20, right: 12, bottom: 40, left: 36 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;
  const max = Math.max(...data.map((d) => d.errorCount), 1);
  const barW = innerW / data.length - 8;

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full max-w-2xl border border-rule rounded-card bg-surface"
      role="img"
      aria-label="班级错题对比柱图"
    >
      {/* Y 轴网格线 */}
      {[0, 0.5, 1].map((r, i) => {
        const y = PAD.top + innerH * r;
        const v = Math.round(max * (1 - r));
        return (
          <g key={`grid-${i}`}>
            <line
              x1={PAD.left}
              y1={y}
              x2={W - PAD.right}
              y2={y}
              stroke="var(--color-rule)"
              strokeWidth={1}
              strokeDasharray="3 3"
            />
            <text
              x={PAD.left - 8}
              y={y + 4}
              textAnchor="end"
              fontSize="10"
              fontFamily="var(--font-family-mono)"
              fill="var(--color-ink-muted)"
            >
              {v}
            </text>
          </g>
        );
      })}
      {/* 柱子 */}
      {data.map((d, i) => {
        const x = PAD.left + i * (barW + 8) + 4;
        const h = (d.errorCount / max) * innerH;
        const y = PAD.top + innerH - h;
        return (
          <g key={d.classId}>
            <rect
              x={x}
              y={y}
              width={barW}
              height={h}
              fill="var(--color-accent)"
              fillOpacity={0.85}
            />
            <text
              x={x + barW / 2}
              y={y - 4}
              textAnchor="middle"
              fontSize="11"
              fontFamily="var(--font-family-mono)"
              fontWeight="600"
              fill="var(--color-ink)"
            >
              {d.errorCount}
            </text>
            <text
              x={x + barW / 2}
              y={H - PAD.bottom + 14}
              textAnchor="middle"
              fontSize="10"
              fontFamily="var(--font-family-sans)"
              fill="var(--color-ink-muted)"
            >
              {d.className}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

/** 章节薄弱度横向柱图 */
function ChapterWeaknessChart({
  data,
}: {
  data: ErrorBookChapterWeakness[];
}): React.ReactNode {
  const W = 540;
  const rowH = 24;
  const labelW = 120;
  const barAreaW = W - labelW - 80;
  const H = data.length * rowH + 20;
  const max = Math.max(...data.map((d) => d.errorCount), 1);

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full max-w-2xl border border-rule rounded-card bg-surface"
      role="img"
      aria-label="章节薄弱度横向柱图"
    >
      {data.map((d, i) => {
        const y = i * rowH + 10;
        const w = (d.errorCount / max) * barAreaW;
        return (
          <g key={d.chapter}>
            <text
              x={0}
              y={y + 14}
              fontSize="11"
              fontFamily="var(--font-family-sans)"
              fill="var(--color-ink)"
            >
              {d.chapter.length > 8 ? d.chapter.slice(0, 8) + "…" : d.chapter}
            </text>
            <rect
              x={labelW}
              y={y}
              width={w}
              height={16}
              fill="var(--color-warning)"
              fillOpacity={0.85}
            />
            <text
              x={labelW + w + 6}
              y={y + 13}
              fontSize="11"
              fontFamily="var(--font-family-mono)"
              fontWeight="600"
              fill="var(--color-ink)"
            >
              {d.errorCount}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

/** 知识点薄弱度雷达图（10 轴） */
function KpWeaknessRadar({
  data,
}: {
  data: ErrorBookKpWeakness[];
}): React.ReactNode {
  const W = 360;
  const H = 320;
  const cx = W / 2;
  const cy = H / 2;
  const r = 110;
  const total = data.length;

  function angleAt(i: number): number {
    return (2 * Math.PI * i) / total - Math.PI / 2;
  }

  function point(i: number, value: number): { x: number; y: number } {
    const a = angleAt(i);
    const radius = (value / 100) * r;
    return { x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) };
  }

  // 雷达形状路径
  const path = data
    .map((d, i) => {
      const p = point(i, d.errorRate * 100);
      return `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`;
    })
    .join(" ") + " Z";

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full max-w-md border border-rule rounded-card bg-surface"
      role="img"
      aria-label="知识点薄弱度雷达图"
    >
      {/* 同心多边形 */}
      {[0.25, 0.5, 0.75, 1].map((ratio, ri) => {
        const pts = data
          .map((_, i) => {
            const a = angleAt(i);
            const radius = r * ratio;
            return `${cx + radius * Math.cos(a)},${cy + radius * Math.sin(a)}`;
          })
          .join(" ");
        return (
          <polygon
            key={`ring-${ri}`}
            points={pts}
            fill="none"
            stroke="var(--color-rule)"
            strokeWidth={1}
          />
        );
      })}
      {/* 轴线 */}
      {data.map((d, i) => {
        const a = angleAt(i);
        const x = cx + r * Math.cos(a);
        const y = cy + r * Math.sin(a);
        return (
          <line
            key={`axis-${i}`}
            x1={cx}
            y1={cy}
            x2={x}
            y2={y}
            stroke="var(--color-rule)"
            strokeWidth={1}
          />
        );
      })}
      {/* 数据形状 */}
      <path
        d={path}
        fill="var(--color-danger)"
        fillOpacity={0.18}
        stroke="var(--color-danger)"
        strokeWidth={2}
      />
      {/* 轴标签 */}
      {data.map((d, i) => {
        const a = angleAt(i);
        const lx = cx + (r + 14) * Math.cos(a);
        const ly = cy + (r + 14) * Math.sin(a);
        return (
          <text
            key={`label-${i}`}
            x={lx}
            y={ly}
            textAnchor="middle"
            fontSize="9"
            fontFamily="var(--font-family-sans)"
            fill="var(--color-ink-muted)"
          >
            {d.knowledgePoint.length > 5
              ? d.knowledgePoint.slice(0, 5) + "…"
              : d.knowledgePoint}
          </text>
        );
      })}
    </svg>
  );
}

export default function ErrorBookPage(): JSX.Element {
  const [subject, setSubject] = useState<string>("数学");
  const [classId, setClassId] = useState<string>("");

  const [result] = useQuery({
    query: ErrorBookQuery,
    variables: { subject, classId: classId || null },
  });

  const book: ErrorBookType | undefined = result.data?.errorBook;

  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 ErrorBookQuery · 学科 × 班级错题多维分析（P7-insights，MSW mock）
        </p>
      </header>

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

      {/* 学科 Tab + 班级筛选 */}
      <div className="mb-6 flex items-baseline justify-between flex-wrap gap-4">
        <div className="flex gap-2">
          {SUBJECTS.map((s) => {
            const active = s === subject;
            return (
              <button
                key={s}
                type="button"
                onClick={() => setSubject(s)}
                className={`px-3 py-1.5 text-sm rounded-button transition-colors ${
                  active
                    ? "text-ink-on-accent bg-accent"
                    : "text-ink border border-rule hover:bg-subtle"
                }`}
              >
                {s}
              </button>
            );
          })}
        </div>
        <div className="flex items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            班级
          </label>
          <select
            value={classId}
            onChange={(e) => setClassId(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"
          >
            {CLASSES.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      {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>
      ) : !book ? (
        <Empty title="暂无数据" description="该学科/班级暂无错题分析" />
      ) : (
        <>
          {/* 5 项统计卡片 */}
          <section className="mb-8 grid grid-cols-2 md:grid-cols-5 gap-4">
            <div className="p-5 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                错题总数
              </p>
              <p className="mt-2 text-3xl font-serif text-ink">
                {book.summary.totalErrors}
              </p>
            </div>
            <div className="p-5 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                高频错题
              </p>
              <p className="mt-2 text-3xl font-serif text-danger">
                {book.summary.highFreqErrors}
              </p>
            </div>
            <div className="p-5 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                薄弱知识点
              </p>
              <p className="mt-2 text-3xl font-serif text-warning">
                {book.summary.weakKpCount}
              </p>
            </div>
            <div className="p-5 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                平均错误率
              </p>
              <p className="mt-2 text-3xl font-serif text-ink">
                {Math.round(book.summary.avgErrorRate * 100)}%
              </p>
            </div>
            <div className="p-5 border border-rule rounded-card">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                上升趋势
              </p>
              <p
                className={`mt-2 text-3xl font-serif ${
                  book.summary.trendUp ? "text-danger" : "text-success"
                }`}
              >
                {book.summary.trendUp ? "↑" : "↓"}
              </p>
            </div>
          </section>

          {/* 班级对比柱图 */}
          <section className="mb-8">
            <h2 className="text-xl font-serif text-ink mb-4">班级对比</h2>
            <div className="rule-thin mb-6" />
            <ClassComparisonChart data={book.classComparison} />
          </section>

          {/* 章节薄弱度 + 知识点薄弱度雷达图 */}
          <section className="mb-8 grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">
                章节薄弱度
              </h2>
              <div className="rule-thin mb-6" />
              <ChapterWeaknessChart data={book.chapterWeakness} />
            </div>
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">
                知识点薄弱度雷达
              </h2>
              <div className="rule-thin mb-6" />
              <KpWeaknessRadar data={book.kpWeakness} />
            </div>
          </section>

          {/* 学生错题分组 */}
          <section className="mb-8">
            <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>
                {book.studentGroups.map((g) => (
                  <tr key={g.studentId} className="border-b border-rule align-top">
                    <td className="py-3 pr-4 text-ink">{g.studentName}</td>
                    <td className="py-3 pr-4 font-mono text-accent">
                      {g.errorCount}
                    </td>
                    <td className="py-3 pr-4">
                      <ul className="space-y-1">
                        {g.topErrors.map((e) => (
                          <li key={e.questionId} className="text-tiny text-ink-muted">
                            <span className="font-mono text-danger">
                              {Math.round(e.errorRate * 100)}%
                            </span>
                            {" "}
                            {e.content.slice(0, 60)}
                            {e.content.length > 60 ? "…" : ""}
                          </li>
                        ))}
                      </ul>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>

          {/* Top10 高频错题 */}
          <section>
            <h2 className="text-xl font-serif text-ink mb-4">
              Top 10 高频错题
            </h2>
            <div className="rule-thin mb-6" />
            <ol className="space-y-2">
              {book.topQuestions.map((q, i) => (
                <li
                  key={q.questionId}
                  className="py-3 px-4 border border-rule rounded-card bg-surface"
                >
                  <div className="flex items-baseline gap-3">
                    <span className="text-lg font-serif text-ink-muted">
                      {i + 1}
                    </span>
                    <div className="flex-1">
                      <p className="text-sm text-ink">
                        {q.content.slice(0, 100)}
                        {q.content.length > 100 ? "…" : ""}
                      </p>
                      <p className="mt-1 text-tiny text-ink-muted font-mono">
                        错误率 {Math.round(q.errorRate * 100)}% · 学科 {q.subject}
                      </p>
                    </div>
                  </div>
                </li>
              ))}
            </ol>
          </section>
        </>
      )}
    </div>
  );
}
