// 学习趋势页面
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/trend
// 对标 student-portal /dashboard/trend

"use client";

import { useState } from "react";
import {
  LineChart,
  Line,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from "recharts";
import { useChildTrend, type TrendPeriod } from "@/hooks/useChildTrend";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { PERMISSIONS } from "@/lib/permissions";
import { usePermission } from "@/hooks/usePermission";

const PERIOD_LABELS: Record<TrendPeriod, string> = {
  week: "本周",
  month: "本月",
  semester: "本学期",
};

const PERIOD_OPTIONS: TrendPeriod[] = ["week", "month", "semester"];

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

const TREND_COLORS: Record<string, string> = {
  up: "hsl(var(--success))",
  down: "hsl(var(--danger))",
  stable: "hsl(var(--ink-muted))",
};

function formatDate(dateStr: string): string {
  const d = new Date(dateStr);
  return `${d.getMonth() + 1}/${d.getDate()}`;
}

export default function TrendPage() {
  const [period, setPeriod] = useState<TrendPeriod>("month");
  const {
    dataPoints,
    avgScore,
    maxScore,
    minScore,
    trendDirection,
    loading,
    error,
  } = useChildTrend(period);
  const { children: childList, currentChildId } = useChildSwitcher();
  const { hasPermission } = usePermission();

  if (!hasPermission(PERMISSIONS.CHILD_TREND_VIEW)) {
    return (
      <div className="flex min-h-[400px] items-center justify-center">
        <p className="text-ink-muted">无权限访问此页面</p>
      </div>
    );
  }

  if (childList.length === 0) {
    return (
      <div className="flex min-h-[400px] items-center justify-center">
        <p className="text-ink-muted">未绑定子女，无法查看学习趋势</p>
      </div>
    );
  }

  const currentChild = childList.find((c) => c.id === currentChildId);

  // 按科目分组
  const subjects = [
    ...new Set(dataPoints.map((d) => d.subject).filter(Boolean)),
  ];
  const chartData = dataPoints.map((d) => ({
    date: formatDate(d.date),
    score: d.score,
    subject: d.subject ?? "综合",
  }));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-serif text-2xl">学习趋势</h1>
          {currentChild && (
            <p className="mt-1 text-sm text-ink-muted">
              {currentChild.name} · {currentChild.grade}
            </p>
          )}
        </div>
        {/* 周期选择器 */}
        <div
          className="flex gap-1 rounded-lg border border-rule p-1"
          role="tablist"
        >
          {PERIOD_OPTIONS.map((p) => (
            <button
              key={p}
              type="button"
              role="tab"
              aria-selected={period === p}
              onClick={() => setPeriod(p)}
              className={
                period === p
                  ? "rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-paper"
                  : "rounded-md px-3 py-1.5 text-sm text-ink-muted hover:text-ink"
              }
            >
              {PERIOD_LABELS[p]}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="space-y-4" role="status" aria-live="polite">
          <div className="skeleton h-64 w-full rounded-lg" />
        </div>
      ) : error ? (
        <div
          className="rounded-lg border border-danger p-4 text-danger"
          role="alert"
        >
          <p>加载失败：{error.message}</p>
          <button
            type="button"
            onClick={() => window.location.reload()}
            className="mt-2 text-sm underline"
          >
            重试
          </button>
        </div>
      ) : dataPoints.length === 0 ? (
        <div className="flex min-h-[300px] items-center justify-center rounded-lg border border-rule">
          <p className="text-ink-muted">暂无趋势数据</p>
        </div>
      ) : (
        <>
          {/* 汇总统计卡片 */}
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
            <div className="rounded-lg border border-rule p-4">
              <p className="text-sm text-ink-muted">平均分</p>
              <p className="mt-1 text-2xl font-serif">{avgScore}</p>
            </div>
            <div className="rounded-lg border border-rule p-4">
              <p className="text-sm text-ink-muted">最高分</p>
              <p className="mt-1 text-2xl font-serif text-success">
                {maxScore}
              </p>
            </div>
            <div className="rounded-lg border border-rule p-4">
              <p className="text-sm text-ink-muted">最低分</p>
              <p className="mt-1 text-2xl font-serif text-danger">{minScore}</p>
            </div>
            <div className="rounded-lg border border-rule p-4">
              <p className="text-sm text-ink-muted">趋势</p>
              <p
                className="mt-1 text-2xl font-serif"
                style={{ color: TREND_COLORS[trendDirection] }}
              >
                {TREND_LABELS[trendDirection]}
              </p>
            </div>
          </div>

          {/* 趋势折线图 */}
          <div className="rounded-lg border border-rule p-4">
            <h2 className="mb-4 font-serif text-lg">成绩变化趋势</h2>
            <ResponsiveContainer width="100%" height={320}>
              <LineChart
                data={chartData}
                margin={{ top: 8, right: 16, bottom: 8, left: 0 }}
              >
                <CartesianGrid
                  strokeDasharray="3 3"
                  stroke="hsl(var(--rule))"
                />
                <XAxis
                  dataKey="date"
                  stroke="hsl(var(--ink-muted))"
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                />
                <YAxis
                  stroke="hsl(var(--ink-muted))"
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                  domain={[0, 100]}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: "hsl(var(--paper-elevated))",
                    border: "1px solid hsl(var(--rule))",
                    borderRadius: "var(--radius-md)",
                    fontSize: "0.875rem",
                  }}
                  labelStyle={{ color: "hsl(var(--ink))" }}
                />
                {subjects.length > 1 ? (
                  subjects.map((subject) => (
                    <Line
                      key={subject}
                      type="monotone"
                      dataKey="score"
                      data={chartData.filter((d) => d.subject === subject)}
                      name={subject}
                      stroke="hsl(var(--accent))"
                      strokeWidth={2}
                      dot={{ r: 3, fill: "hsl(var(--accent))" }}
                      activeDot={{ r: 5 }}
                    />
                  ))
                ) : (
                  <Line
                    type="monotone"
                    dataKey="score"
                    stroke="hsl(var(--accent))"
                    strokeWidth={2}
                    dot={{ r: 3, fill: "hsl(var(--accent))" }}
                    activeDot={{ r: 5 }}
                  />
                )}
                {subjects.length > 1 && <Legend />}
              </LineChart>
            </ResponsiveContainer>
          </div>

          {/* 明细列表 */}
          <div className="rounded-lg border border-rule">
            <div className="border-b border-rule px-4 py-3">
              <h2 className="font-serif text-lg">详细数据</h2>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-rule text-left text-ink-muted">
                    <th className="px-4 py-2 font-normal">日期</th>
                    <th className="px-4 py-2 font-normal">科目</th>
                    <th className="px-4 py-2 font-normal text-right">分数</th>
                  </tr>
                </thead>
                <tbody>
                  {dataPoints.map((d, i) => (
                    <tr key={i} className="border-b border-rule last:border-0">
                      <td className="px-4 py-2">{formatDate(d.date)}</td>
                      <td className="px-4 py-2">{d.subject ?? "综合"}</td>
                      <td className="px-4 py-2 text-right font-mono">
                        {d.score}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
