"use client";

/**
 * 班级详情聚合页 - 单班级完整信息
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ClassDetailQuery：聚合班级信息 + 学生 + 课表 + 近期作业 + 概览统计 + 成绩趋势
 *
 * 布局：多 widget 用 ErrorBoundary 隔离，单个 widget 异常不影响整页
 *
 * 维护者：ai13（teacher-portal）
 */

import { useQuery } from "urql";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ErrorBoundary, Loading, Empty } from "@edu/ui-components";
import { ClassDetailQuery } from "@/lib/graphql-p7-admin";
import type {
  ClassDetailAggregate,
  ClassDetailTrendPoint,
  ClassScheduleItem,
  ClassDetailHomework,
} from "@/lib/graphql-p7-admin";

const DAY_LABELS: Record<number, string> = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  7: "周日",
};

function todayDayOfWeek(): number {
  const d = new Date().getDay(); // 0 = Sunday
  return d === 0 ? 7 : d;
}

/** 班级成绩趋势 mini chart（纯 SVG） */
function TrendMiniChart({ data }: { data: ClassDetailTrendPoint[] }): React.ReactNode {
  if (data.length === 0) {
    return <p className="text-tiny text-ink-muted">暂无趋势数据</p>;
  }
  const W = 280;
  const H = 96;
  const PAD = { top: 12, right: 12, bottom: 18, left: 24 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;
  const values = data.map((d) => d.avgScore);
  const yMax = Math.max(100, ...values);
  const yMin = Math.min(0, ...values);
  const yRange = yMax - yMin || 1;
  const xStep = data.length > 1 ? innerW / (data.length - 1) : 0;
  const toPoint = (v: number, i: number) => ({
    x: PAD.left + i * xStep,
    y: PAD.top + innerH - ((v - yMin) / yRange) * innerH,
  });
  const path = data
    .map((d, i) => {
      const p = toPoint(d.avgScore, i);
      return `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`;
    })
    .join(" ");
  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      className="w-full border border-rule rounded-card bg-surface"
      role="img"
      aria-label="班级成绩趋势图"
    >
      {[0, 50, 100].map((v) => {
        const ratio = 1 - (v - yMin) / yRange;
        const y = PAD.top + innerH * ratio;
        return (
          <g key={`grid-${v}`}>
            <line
              x1={PAD.left}
              y1={y}
              x2={W - PAD.right}
              y2={y}
              stroke="var(--color-rule)"
              strokeWidth={1}
              strokeDasharray="2 2"
            />
            <text
              x={PAD.left - 6}
              y={y + 3}
              textAnchor="end"
              fontSize="9"
              fontFamily="var(--font-family-mono)"
              fill="var(--color-ink-muted)"
            >
              {v}
            </text>
          </g>
        );
      })}
      <path
        d={path}
        fill="none"
        stroke="var(--color-accent)"
        strokeWidth={2}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      {data.map((d, i) => {
        const p = toPoint(d.avgScore, i);
        return (
          <g key={`pt-${i}`}>
            <circle
              cx={p.x}
              cy={p.y}
              r={3}
              fill="var(--color-accent)"
              stroke="var(--bg-paper)"
              strokeWidth={1}
            />
            <text
              x={p.x}
              y={H - 4}
              textAnchor="middle"
              fontSize="9"
              fontFamily="var(--font-family-sans)"
              fill="var(--color-ink-muted)"
            >
              {d.month}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

/** 概览统计卡片 */
function OverviewCard({
  label,
  value,
  suffix,
}: {
  label: string;
  value: string | number;
  suffix?: string;
}): React.ReactNode {
  return (
    <div className="p-4 border border-rule rounded-card bg-surface">
      <p className="text-tiny uppercase tracking-wide text-ink-muted">{label}</p>
      <p className="mt-2 text-2xl font-serif text-ink">
        {value}
        {suffix && (
          <span className="ml-1 text-sm font-sans text-ink-muted">{suffix}</span>
        )}
      </p>
    </div>
  );
}

/** 近期作业 widget */
function HomeworkWidget({
  items,
}: {
  items: ClassDetailHomework[];
}): React.ReactNode {
  return (
    <section>
      <h3 className="mb-3 text-lg font-serif text-ink">近期作业</h3>
      <div className="rule-thin mb-3" />
      {items.length === 0 ? (
        <p className="text-sm text-ink-muted">暂无作业</p>
      ) : (
        <ul className="space-y-0">
          {items.map((h) => (
            <li
              key={h.id}
              className="py-2 grid grid-cols-12 gap-2 items-baseline border-b border-rule"
            >
              <div className="col-span-5">
                <p className="text-sm font-serif text-ink">{h.title}</p>
              </div>
              <div className="col-span-3 text-tiny font-mono text-ink-muted">
                {h.dueDate}
              </div>
              <div className="col-span-2 text-tiny font-mono text-ink-muted">
                提交率 {h.submissionRate}%
              </div>
              <div className="col-span-2 text-right text-tiny font-mono text-ink-muted">
                {h.avgScore === null ? "未评" : `均分 ${h.avgScore}`}
              </div>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}

/** 本周课表 widget */
function ScheduleWidget({
  schedule,
}: {
  schedule: ClassScheduleItem[];
}): React.ReactNode {
  const today = todayDayOfWeek();
  const todayItems = schedule
    .filter((s) => s.dayOfWeek === today && today <= 5)
    .sort((a, b) => a.period - b.period);
  return (
    <section>
      <h3 className="mb-3 text-lg font-serif text-ink">
        今日课表
        <span className="ml-2 text-tiny font-sans text-ink-muted">
          {DAY_LABELS[today] ?? "—"}
        </span>
      </h3>
      <div className="rule-thin mb-3" />
      {todayItems.length === 0 ? (
        <p className="text-sm text-ink-muted">今日无课</p>
      ) : (
        <ul className="space-y-0">
          {todayItems.map((s) => (
            <li
              key={s.id}
              className="py-2 grid grid-cols-12 gap-2 items-baseline border-b border-rule"
            >
              <div className="col-span-1 text-tiny font-mono text-ink-muted">
                {s.period}
              </div>
              <div className="col-span-2 text-tiny font-mono text-ink-muted">
                {s.startTime}-{s.endTime}
              </div>
              <div className="col-span-5 text-sm font-serif text-ink">
                {s.subject}
              </div>
              <div className="col-span-2 text-tiny text-ink-muted">
                {s.teacherName}
              </div>
              <div className="col-span-2 text-right text-tiny font-mono text-ink-muted">
                {s.room}
              </div>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}

/** 学生列表 widget */
function StudentsWidget({
  classId,
  students,
}: {
  classId: string;
  students: { id: string; name: string; studentNo: string; email: string }[];
}): React.ReactNode {
  return (
    <section>
      <div className="flex items-baseline justify-between mb-3">
        <h3 className="text-lg font-serif text-ink">
          学生列表
          <span className="ml-2 text-tiny font-sans text-ink-muted">
            {students.length} 名
          </span>
        </h3>
        <Link
          href={`/students?classId=${classId}`}
          className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
        >
          查看全部 →
        </Link>
      </div>
      <div className="rule-thin mb-3" />
      <ul className="grid grid-cols-2 gap-x-6 gap-y-1">
        {students.slice(0, 12).map((s) => (
          <li
            key={s.id}
            className="py-2 grid grid-cols-12 gap-2 items-baseline border-b border-rule"
          >
            <div className="col-span-5 text-sm font-serif text-ink">{s.name}</div>
            <div className="col-span-5 text-tiny font-mono text-ink-muted">
              {s.studentNo}
            </div>
            <div className="col-span-2 text-right text-tiny">
              <Link
                href={`/students/${s.id}`}
                className="font-mono text-ink-muted hover:text-accent"
              >
                详情
              </Link>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}

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

  const [result] = useQuery({
    query: ClassDetailQuery,
    variables: { id: classId },
    pause: !classId,
  });

  if (!classId) {
    return (
      <div className="px-10 py-10">
        <Empty title="未指定班级" description="请从班级列表进入详情页" />
      </div>
    );
  }

  if (result.fetching) {
    return (
      <div className="px-10 py-10">
        <Loading lines={6} />
      </div>
    );
  }

  if (result.error) {
    return (
      <div className="px-10 py-10">
        <header className="mb-8">
          <Link
            href="/classes"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回班级列表
          </Link>
          <h1 className="mt-2 text-3xl font-serif text-ink">班级详情</h1>
        </header>
        <div className="rule-thin mb-8" />
        <div className="mark-left py-2 mb-4 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      </div>
    );
  }

  const data = result.data?.classDetail as ClassDetailAggregate | undefined;
  if (!data) {
    return (
      <div className="px-10 py-10">
        <Empty title="班级不存在" description="未找到该班级的详情数据" />
      </div>
    );
  }

  const cls = data.class;
  const overview = data.overview;

  return (
    <div className="px-10 py-10">
      {/* 头部 */}
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href="/classes"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回班级列表
          </Link>
        </p>
        <div className="flex items-baseline justify-between">
          <div>
            <h1 className="text-3xl font-serif text-ink">{cls.name}</h1>
            <p className="mt-1 text-sm text-ink-muted">
              GraphQL ClassDetailQuery · 班级详情聚合（P7 扩展，MSW mock）
            </p>
          </div>
          <Link
            href={`/classes/schedule?classId=${cls.id}`}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            查看完整课表
          </Link>
        </div>
      </header>

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

      {/* 班级信息 */}
      <section className="mb-8 grid grid-cols-4 gap-4">
        <div>
          <p className="text-tiny uppercase tracking-wide text-ink-muted">学科</p>
          <p className="mt-1 text-sm font-serif text-ink">{cls.subject}</p>
        </div>
        <div>
          <p className="text-tiny uppercase tracking-wide text-ink-muted">学生数</p>
          <p className="mt-1 text-sm font-serif text-ink">
            {cls.studentCount} 名
          </p>
        </div>
        <div>
          <p className="text-tiny uppercase tracking-wide text-ink-muted">班主任</p>
          <p className="mt-1 text-sm font-serif text-ink">
            {cls.homeroomTeacher}
          </p>
        </div>
        <div>
          <p className="text-tiny uppercase tracking-wide text-ink-muted">教室</p>
          <p className="mt-1 text-sm font-mono text-ink">{cls.room ?? "—"}</p>
        </div>
      </section>

      {/* 概览统计卡片 */}
      <ErrorBoundary
        fallback={
          <p className="text-tiny text-danger">概览统计加载失败</p>
        }
      >
        <section className="mb-8">
          <h2 className="mb-4 text-xl font-serif text-ink">概览统计</h2>
          <div className="rule-thin mb-4" />
          <div className="grid grid-cols-4 gap-4">
            <OverviewCard
              label="出勤率"
              value={overview.attendanceRate.toFixed(1)}
              suffix="%"
            />
            <OverviewCard
              label="平均分"
              value={overview.averageScore.toFixed(1)}
            />
            <OverviewCard
              label="作业完成率"
              value={overview.homeworkCompletionRate.toFixed(1)}
              suffix="%"
            />
            <OverviewCard
              label="最近考试"
              value={
                overview.recentExamTitle
                  ? `${overview.recentExamAvg ?? "—"}`
                  : "无"
              }
              suffix={
                overview.recentExamTitle
                  ? `(均分 ${overview.recentExamAvg ?? "—"})`
                  : undefined
              }
            />
          </div>
          {overview.recentExamTitle && (
            <p className="mt-2 text-tiny text-ink-muted">
              最近考试：{overview.recentExamTitle}
            </p>
          )}
        </section>
      </ErrorBoundary>

      {/* 双列布局：左列作业 + 学生；右列课表 + 趋势 */}
      <div className="grid grid-cols-2 gap-8">
        <ErrorBoundary
          fallback={<p className="text-tiny text-danger">作业模块加载失败</p>}
        >
          <HomeworkWidget items={data.recentHomework} />
        </ErrorBoundary>

        <ErrorBoundary
          fallback={<p className="text-tiny text-danger">课表模块加载失败</p>}
        >
          <ScheduleWidget schedule={data.schedule} />
        </ErrorBoundary>

        <ErrorBoundary
          fallback={<p className="text-tiny text-danger">学生列表加载失败</p>}
        >
          <StudentsWidget classId={cls.id} students={data.students} />
        </ErrorBoundary>

        <ErrorBoundary
          fallback={<p className="text-tiny text-danger">趋势图加载失败</p>}
        >
          <section>
            <h3 className="mb-3 text-lg font-serif text-ink">成绩趋势</h3>
            <div className="rule-thin mb-3" />
            <TrendMiniChart data={data.trend} />
          </section>
        </ErrorBoundary>
      </div>
    </div>
  );
}
