"use client";

/**
 * 作业提交评审列表
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL HomeworkSubmissionsQuery：按作业维度统计提交/已批数
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 列出所有作业的提交统计，"去批改" 链接跳转批量批改视图
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import { HomeworkSubmissionsQuery } from "@/lib/graphql-p7-grades";
import type { HomeworkSubmissionStat } from "@/lib/graphql-p7-grades";

/** 状态中文映射 */
const STATUS_LABEL: Record<string, string> = {
  draft: "草稿",
  published: "已发布",
  graded: "已批改",
};

export default function HomeworkSubmissionsPage(): React.ReactNode {
  const [classId, setClassId] = useState("");
  const [status, setStatus] = useState("");

  // 班级列表
  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];

  // 提交统计
  const [result] = useQuery({
    query: HomeworkSubmissionsQuery,
    variables: {
      classId: classId || null,
      status: status || null,
    },
  });

  const stats: HomeworkSubmissionStat[] =
    result.data?.homeworkSubmissions ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href="/homework"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回作业管理
          </Link>
        </p>
        <h1 className="text-3xl font-serif text-ink">作业提交评审</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL HomeworkSubmissionsQuery · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {/* 筛选区 */}
      <section className="mb-8">
        <div className="grid grid-cols-2 gap-6">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              班级
            </label>
            <select
              value={classId}
              onChange={(e) => setClassId(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              <option value="">全部班级</option>
              {classes.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              状态
            </label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              <option value="">全部状态</option>
              <option value="draft">草稿</option>
              <option value="published">已发布</option>
              <option value="graded">已批改</option>
            </select>
          </div>
        </div>
      </section>

      {result.fetching ? (
        <Loading lines={6} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : stats.length === 0 ? (
        <Empty title="暂无提交" description="没有符合条件的作业提交记录" />
      ) : (
        <section>
          <div className="border border-rule rounded-card overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-subtle">
                <tr>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    作业
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    班级
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    状态
                  </th>
                  <th className="px-4 py-3 text-right text-tiny uppercase tracking-wide text-ink-muted">
                    已提交/总数
                  </th>
                  <th className="px-4 py-3 text-right text-tiny uppercase tracking-wide text-ink-muted">
                    已批/已提交
                  </th>
                  <th className="px-4 py-3 text-right text-tiny uppercase tracking-wide text-ink-muted">
                    平均分
                  </th>
                  <th className="px-4 py-3 text-right text-tiny uppercase tracking-wide text-ink-muted">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody>
                {stats.map((s) => {
                  const submitRate =
                    s.totalCount > 0
                      ? Math.round((s.submittedCount / s.totalCount) * 100)
                      : 0;
                  const gradeRate =
                    s.submittedCount > 0
                      ? Math.round((s.gradedCount / s.submittedCount) * 100)
                      : 0;
                  return (
                    <tr key={s.homeworkId} className="border-t border-rule">
                      <td className="px-4 py-3 font-serif text-ink">
                        {s.title}
                      </td>
                      <td className="px-4 py-3 text-sm text-ink-muted">
                        {s.className}
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-tiny text-ink-muted">
                          {STATUS_LABEL[s.status] ?? s.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-mono text-tiny text-ink">
                        {s.submittedCount}/{s.totalCount}
                        <span className="ml-1 text-ink-muted">
                          ({submitRate}%)
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-mono text-tiny text-ink">
                        {s.gradedCount}/{s.submittedCount}
                        <span className="ml-1 text-ink-muted">
                          ({gradeRate}%)
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-serif text-accent">
                        {s.avgScore !== null ? s.avgScore : "—"}
                      </td>
                      <td className="px-4 py-3 text-right">
                        <Link
                          href={`/homework/assignments/${s.homeworkId}/submissions`}
                          className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                        >
                          去批改
                        </Link>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </section>
      )}
    </div>
  );
}
