"use client";

/**
 * Students 页面 - 班级学生名单
 *
 * 数据来源（contract.md §2.4）：GraphQL ClassStudentsQuery（P3 扩展，MSW mock）
 * - 通过 URL ?classId=xxx 指定班级
 * - P2 阶段用 MSW mock 数据，待 teacher-bff P3 启用 iam 聚合
 *
 * 维护者：ai13（teacher-portal）
 */

import { useQuery } from "urql";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { Loading, Empty } from "@edu/ui-components";
import { ClassStudentsQuery, ClassQuery } from "@/lib/graphql";
import type { Student } from "@/lib/graphql";

function StudentsContent() {
  const searchParams = useSearchParams();
  const classId = searchParams.get("classId") ?? "";

  // 班级详情（用于显示班级名称）
  const [classResult] = useQuery({
    query: ClassQuery,
    variables: { id: classId },
    pause: !classId,
  });

  // 学生名单
  const [studentsResult] = useQuery({
    query: ClassStudentsQuery,
    variables: { classId },
    pause: !classId,
  });

  if (!classId) {
    return (
      <div className="px-10 py-10">
        <Empty title="未指定班级" description="请从班级列表进入查看学生名单" />
      </div>
    );
  }

  const cls = classResult.data?.class;
  const students = studentsResult.data?.classStudents ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">
          {cls ? `${cls.name} - 学生名单` : "学生名单"}
        </h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL ClassStudentsQuery · iam 数据聚合（P3 扩展，MSW mock）
        </p>
      </header>

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

      {studentsResult.fetching ? (
        <Loading lines={6} />
      ) : studentsResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{studentsResult.error.message}
          </p>
        </div>
      ) : students.length === 0 ? (
        <Empty title="暂无学生" description="该班级尚未录入学生信息" />
      ) : (
        <ul className="space-y-0">
          {(students as Student[]).map((s) => (
            <li
              key={s.id}
              className="py-4 grid grid-cols-12 gap-4 items-center border-b border-rule"
            >
              <div className="col-span-5">
                <h3 className="text-lg font-serif text-ink">{s.name}</h3>
                <p className="mt-1 text-tiny text-ink-muted">{s.email}</p>
              </div>
              <div className="col-span-5 text-sm text-ink-muted">
                ID: {s.id}
              </div>
              <div className="col-span-2 text-right text-tiny font-mono text-ink-muted">
                {s.id.slice(0, 8)}...
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function StudentsPage() {
  return (
    <Suspense
      fallback={
        <div className="px-10 py-10">
          <Loading lines={3} />
        </div>
      }
    >
      <StudentsContent />
    </Suspense>
  );
}
