"use client";

/**
 * Homework 页面 - 作业管理
 *
 * 数据来源（contract.md §2.4）：GraphQL ClassHomeworkQuery（P3 扩展，MSW mock）
 * - 通过 URL ?classId=xxx 指定班级
 * - P2 阶段用 MSW mock 数据，待 teacher-bff P3 启用 core-edu 聚合
 * - P3：列表项可点击进入详情页（批改界面），顶部提供"布置作业"入口
 *
 * 维护者：ai13（teacher-portal）
 */

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

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

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

  const [homeworkResult] = useQuery({
    query: ClassHomeworkQuery,
    variables: { classId },
    pause: !classId,
  });

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

  const cls = classResult.data?.class;
  const items = homeworkResult.data?.classHomework ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <h1 className="text-3xl font-serif text-ink">
            {cls ? `${cls.name} - 作业管理` : "作业管理"}
          </h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL ClassHomeworkQuery · core-edu 域（P3 扩展，MSW mock）
          </p>
        </div>
        <Link
          href={`/homework/new?classId=${classId}`}
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          布置作业
        </Link>
      </header>

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

      {homeworkResult.fetching ? (
        <Loading lines={4} />
      ) : homeworkResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{homeworkResult.error.message}
          </p>
        </div>
      ) : items.length === 0 ? (
        <Empty
          title="暂无作业"
          description="该班级尚未布置作业"
          action={
            <Link
              href={`/homework/new?classId=${classId}`}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
            >
              布置第一份作业
            </Link>
          }
        />
      ) : (
        <ul className="space-y-0">
          {(items as HomeworkItem[]).map((hw) => (
            <li
              key={hw.id}
              className="py-4 grid grid-cols-12 gap-4 items-baseline border-b border-rule hover:bg-subtle"
            >
              <div className="col-span-7">
                <Link href={`/homework/${hw.id}`}>
                  <h3 className="text-lg font-serif text-ink hover:text-accent">
                    {hw.title}
                  </h3>
                </Link>
                {hw.description && (
                  <p className="mt-1 text-sm text-ink-muted">
                    {hw.description}
                  </p>
                )}
                <p className="mt-1 text-tiny text-ink-muted">
                  截止: {new Date(hw.dueDate).toLocaleString("zh-CN")}
                </p>
              </div>
              <div className="col-span-3 text-tiny text-ink-muted">
                状态: {hw.status}
              </div>
              <div className="col-span-2 text-right text-tiny">
                <Link
                  href={`/homework/${hw.id}`}
                  className="font-mono text-ink-muted hover:text-accent"
                >
                  查看详情 →
                </Link>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

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