"use client";

/**
 * 自适应练习分析页（P7-insights）
 *
 * 数据来源：GraphQL PracticeAnalyticsQuery
 *
 * 6 个 Widget：
 * 1. 班级筛选
 * 2. 5 项统计卡片（总练习数/完成率/平均正确率/薄弱知识点/参与度）
 * 3. 班级对比表（5 班级 × 5 指标）
 * 4. 类型分布饼图（5 类型：单选/多选/判断/填空/简答）- 纯 SVG
 * 5. 知识点薄弱度柱图（10 知识点 × 正确率）- 纯 SVG
 * 6. 学生排名表 + 未参与提醒
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import { Loading, Empty } from "@edu/ui-components";
import { PracticeAnalyticsQuery } from "@/lib/graphql-p7-insights";
import type {
  PracticeAnalytics as PracticeAnalyticsType,
  PracticeTypeBreakdown,
  PracticeKpWeakness,
} from "@/lib/graphql-p7-insights";

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)班" },
];

/** 饼图色板（使用语义令牌变量，禁止 hex 字面量） */
const PIE_COLORS = [
  "var(--color-accent)",
  "var(--color-success)",
  "var(--color-warning)",
  "var(--color-danger)",
  "var(--color-ink-muted)",
];

/** 类型分布饼图 */
function TypePieChart({
  data,
}: {
  data: PracticeTypeBreakdown[];
}): React.ReactNode {
  const W = 320;
  const H = 240;
  const cx = W / 2 - 30;
  const cy = H / 2;
  const r = 80;
  const total = data.reduce((acc, d) => acc + d.count, 0) || 1;

  function arcPath(
    startAngle: number,
    endAngle: number,
  ): string {
    const x1 = cx + r * Math.cos(startAngle);
    const y1 = cy + r * Math.sin(startAngle);
    const x2 = cx + r * Math.cos(endAngle);
    const y2 = cy + r * Math.sin(endAngle);
    const largeArc = endAngle - startAngle > Math.PI ? 1 : 0;
    return `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
  }

  let accAngle = -Math.PI / 2;
  const slices = data.map((d, i) => {
    const angle = (d.count / total) * 2 * Math.PI;
    const start = accAngle;
    const end = accAngle + angle;
    accAngle = end;
    return { d, path: arcPath(start, end), color: PIE_COLORS[i % PIE_COLORS.length] ?? PIE_COLORS[0] };
  });

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full max-w-md border border-rule rounded-card bg-surface"
      role="img"
      aria-label="练习类型分布饼图"
    >
      {slices.map((s, i) => (
        <path
          key={i}
          d={s.path}
          fill={s.color}
          fillOpacity={0.85}
          stroke="var(--bg-paper)"
          strokeWidth={2}
        />
      ))}
      {/* 图例 */}
      {slices.map((s, i) => {
        const ly = 20 + i * 20;
        return (
          <g key={`legend-${i}`}>
            <rect
              x={W - 100}
              y={ly - 9}
              width={12}
              height={12}
              fill={s.color}
              fillOpacity={0.85}
            />
            <text
              x={W - 82}
              y={ly}
              fontSize="10"
              fontFamily="var(--font-family-sans)"
              fill="var(--color-ink)"
            >
              {s.d.type}（{Math.round(s.d.ratio * 100)}%）
            </text>
          </g>
        );
      })}
    </svg>
  );
}

/** 知识点薄弱度柱图（垂直柱） */
function KpWeaknessBarChart({
  data,
}: {
  data: PracticeKpWeakness[];
}): React.ReactNode {
  const W = 540;
  const H = 240;
  const PAD = { top: 20, right: 12, bottom: 60, left: 36 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;
  const barW = innerW / data.length - 6;

  function accuracyColor(rate: number): string {
    if (rate >= 0.8) return "var(--color-success)";
    if (rate >= 0.6) return "var(--color-warning)";
    return "var(--color-danger)";
  }

  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(100 * (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 + 6) + 3;
        const h = d.accuracy * innerH;
        const y = PAD.top + innerH - h;
        const color = accuracyColor(d.accuracy);
        return (
          <g key={d.knowledgePoint}>
            <rect
              x={x}
              y={y}
              width={barW}
              height={h}
              fill={color}
              fillOpacity={0.85}
            />
            <text
              x={x + barW / 2}
              y={y - 4}
              textAnchor="middle"
              fontSize="10"
              fontFamily="var(--font-family-mono)"
              fontWeight="600"
              fill="var(--color-ink)"
            >
              {Math.round(d.accuracy * 100)}
            </text>
            <text
              x={x + barW / 2}
              y={H - PAD.bottom + 14}
              textAnchor="middle"
              fontSize="9"
              fontFamily="var(--font-family-sans)"
              fill="var(--color-ink-muted)"
            >
              {d.knowledgePoint.length > 4
                ? d.knowledgePoint.slice(0, 4) + "…"
                : d.knowledgePoint}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

export default function PracticePage(): JSX.Element {
  const [classId, setClassId] = useState<string>("");

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

  const analytics: PracticeAnalyticsType | undefined =
    result.data?.practiceAnalytics;

  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 PracticeAnalyticsQuery · 班级练习统计与未参与提醒（P7-insights）
        </p>
      </header>

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

      {/* 班级筛选 */}
      <div className="mb-6 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>

      {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>
      ) : !analytics ? (
        <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">
                {analytics.summary.totalSessions}
              </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-success">
                {Math.round(analytics.summary.completionRate * 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 text-accent">
                {Math.round(analytics.summary.avgAccuracy * 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 text-warning">
                {analytics.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(analytics.summary.participationRate * 100)}%
              </p>
            </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>
                  <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>
                {analytics.classComparison.map((c) => (
                  <tr key={c.classId} className="border-b border-rule">
                    <td className="py-3 pr-4 text-ink">{c.className}</td>
                    <td className="py-3 pr-4 font-mono text-ink">
                      {c.totalSessions}
                    </td>
                    <td className="py-3 pr-4 font-mono text-success">
                      {Math.round(c.completionRate * 100)}%
                    </td>
                    <td className="py-3 pr-4 font-mono text-accent">
                      {Math.round(c.avgAccuracy * 100)}%
                    </td>
                    <td className="py-3 pr-4 font-mono text-ink-muted">
                      {Math.round(c.participationRate * 100)}%
                    </td>
                    <td className="py-3 pr-4 font-mono text-warning">
                      {c.weakKpCount}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </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" />
              <TypePieChart data={analytics.typeBreakdown} />
            </div>
            <div>
              <h2 className="text-xl font-serif text-ink mb-4">
                知识点正确率
              </h2>
              <div className="rule-thin mb-6" />
              <KpWeaknessBarChart data={analytics.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>
                  <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>
                {analytics.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 font-mono text-ink-muted text-tiny">
                      {r.studentNo}
                    </td>
                    <td className="py-3 pr-4 text-ink">{r.studentName}</td>
                    <td className="py-3 pr-4 font-mono text-ink">
                      {r.totalSessions}
                    </td>
                    <td className="py-3 pr-4 font-mono text-accent">
                      {Math.round(r.accuracy * 100)}%
                    </td>
                    <td className="py-3 pr-4 text-ink-muted">
                      {r.weakKp}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>

          {/* 未参与提醒 */}
          <section>
            <h2 className="text-xl font-serif text-ink mb-4">
              未参与提醒（最近 7 天）
            </h2>
            <div className="rule-thin mb-6" />
            {analytics.inactiveStudents.length === 0 ? (
              <p className="text-sm text-ink-muted">所有学生均积极参与练习 ✓</p>
            ) : (
              <div className="p-4 border border-warning rounded-card bg-warning/10">
                <ul className="space-y-2">
                  {analytics.inactiveStudents.map((s) => (
                    <li
                      key={s.studentId}
                      className="flex items-baseline justify-between text-sm"
                    >
                      <span className="text-ink">{s.studentName}</span>
                      <span className="font-mono text-tiny text-warning">
                        最近 {s.lastActiveDays} 天未练习
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </section>
        </>
      )}
    </div>
  );
}
