"use client";

/**
 * 学习趋势页（ai14，P4，路由 /dashboard/trend）
 *
 * - 消费 useMyTrend 查询
 * - 折线图（recharts）展示历次考试得分趋势
 * - 汇总统计：平均分、最高分、最低分、趋势方向
 */

import { useMemo } from "react";
import {
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { useMyTrend } from "@/lib/graphql/hooks";
import type { TrendDataPoint } from "@/lib/graphql/types";

interface ChartDatum {
  label: string;
  score: number;
}

type TrendDirection = "up" | "down" | "stable";

function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
    });
  } catch {
    return iso;
  }
}

function computeStats(points: TrendDataPoint[]): {
  average: number;
  highest: number;
  lowest: number;
  direction: TrendDirection;
} {
  if (points.length === 0) {
    return { average: 0, highest: 0, lowest: 0, direction: "stable" };
  }
  const scores = points.map((p) => p.score);
  const sum = scores.reduce((acc, s) => acc + s, 0);
  const average = Math.round((sum / scores.length) * 10) / 10;
  const highest = Math.max(...scores);
  const lowest = Math.min(...scores);

  let direction: TrendDirection = "stable";
  if (points.length >= 2) {
    const last = points[points.length - 1]?.score ?? 0;
    const prev = points[points.length - 2]?.score ?? 0;
    if (last - prev > 0.5) direction = "up";
    else if (prev - last > 0.5) direction = "down";
  }
  return { average, highest, lowest, direction };
}

const DIRECTION_LABEL: Record<TrendDirection, string> = {
  up: "上升",
  down: "下降",
  stable: "平稳",
};

function directionColor(dir: TrendDirection): string {
  if (dir === "up") return "var(--color-success)";
  if (dir === "down") return "var(--color-danger)";
  return "var(--color-ink-muted)";
}

export default function TrendPage(): React.ReactNode {
  const { data, fetching, error, reexecute } = useMyTrend();
  const points = data ?? [];
  const stats = useMemo(() => computeStats(points), [points]);
  const chartData = useMemo<ChartDatum[]>(
    () => points.map((p) => ({ label: formatDate(p.date), score: p.score })),
    [points],
  );

  return (
    <main
      className="px-md py-lg max-w-4xl mx-auto"
      aria-labelledby="trend-title"
    >
      <header className="mb-lg">
        <h1 id="trend-title" className="font-serif text-2xl text-ink">
          学习趋势
        </h1>
        <p className="mt-xs text-sm text-ink-muted">历次考试得分趋势</p>
      </header>

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

      {fetching ? (
        <p className="text-sm text-ink-muted" aria-live="polite">
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md mb-md" aria-live="assertive">
          <p className="text-sm text-ink">{error.message || "加载失败"}</p>
          <button
            type="button"
            className="btn-secondary mt-sm"
            onClick={() => reexecute()}
          >
            重试
          </button>
        </div>
      ) : points.length === 0 ? (
        <p className="text-sm text-ink-muted" role="status">
          暂无学习趋势数据
        </p>
      ) : (
        <>
          {/* 汇总统计 */}
          <section
            className="grid grid-cols-2 sm:grid-cols-4 gap-md mb-lg"
            aria-label="趋势汇总"
          >
            <div className="card-paper p-md">
              <p className="text-xs text-ink-subtle">平均分</p>
              <p className="font-serif text-2xl text-ink mt-xs">
                {stats.average}
              </p>
            </div>
            <div className="card-paper p-md">
              <p className="text-xs text-ink-subtle">最高分</p>
              <p className="font-serif text-2xl text-ink mt-xs">
                {stats.highest}
              </p>
            </div>
            <div className="card-paper p-md">
              <p className="text-xs text-ink-subtle">最低分</p>
              <p className="font-serif text-2xl text-ink mt-xs">
                {stats.lowest}
              </p>
            </div>
            <div className="card-paper p-md">
              <p className="text-xs text-ink-subtle">趋势方向</p>
              <p
                className="font-serif text-2xl mt-xs"
                style={{ color: directionColor(stats.direction) }}
              >
                {DIRECTION_LABEL[stats.direction]}
              </p>
            </div>
          </section>

          {/* 趋势折线图 */}
          <section className="card-paper p-lg" aria-label="得分趋势折线图">
            <div style={{ width: "100%", height: 320 }}>
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={chartData}
                  margin={{ top: 8, right: 16, bottom: 8, left: 0 }}
                >
                  <CartesianGrid
                    stroke="var(--color-rule)"
                    strokeDasharray="3 3"
                  />
                  <XAxis
                    dataKey="label"
                    tick={{ fill: "var(--color-ink-muted)", fontSize: 12 }}
                  />
                  <YAxis
                    tick={{ fill: "var(--color-ink-muted)", fontSize: 12 }}
                    domain={["auto", "auto"]}
                  />
                  <Tooltip
                    contentStyle={{
                      background: "var(--color-paper)",
                      border: "1px solid var(--color-rule)",
                      borderRadius: "var(--radius-base)",
                      fontSize: 12,
                    }}
                    labelStyle={{ color: "var(--color-ink)" }}
                  />
                  <Line
                    type="monotone"
                    dataKey="score"
                    stroke="var(--color-accent)"
                    strokeWidth={2}
                    dot={{ r: 3, fill: "var(--color-accent)" }}
                    activeDot={{ r: 5 }}
                    isAnimationActive={false}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </section>
        </>
      )}
    </main>
  );
}
