"use client";

/**
 * 作业批量批改视图
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL HomeworkAssignmentSubmissionsQuery：按作业 ID 拉取所有提交列表
 * - GraphQL AiBatchGradingQuery：批量自动评分建议
 *
 * 顶部统计：已批/已提交/未提交
 * 表格：学生 | 提交时间 | 分数 | 状态 | "批改" 链接
 * "批量自动评分" 按钮触发 AI 评分建议
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery, useMutation } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  HomeworkAssignmentSubmissionsQuery,
  AiBatchGradingQuery,
  GradeSubmissionMutation,
} from "@/lib/graphql-p7-grades";
import type {
  HomeworkSubmissionDetail,
  AiBatchGradingItem,
} from "@/lib/graphql-p7-grades";

/** 状态中文映射 */
const STATUS_LABEL: Record<string, string> = {
  SUBMITTED: "已提交",
  GRADED: "已批改",
};

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

  const [result, reexecuteQuery] = useQuery({
    query: HomeworkAssignmentSubmissionsQuery,
    variables: { homeworkId },
    pause: !homeworkId,
  });

  // AI 批量评分建议（点击按钮后触发）
  const [aiResult, executeAi] = useQuery({
    query: AiBatchGradingQuery,
    variables: { homeworkId },
    pause: true, // 手动触发
  });

  const [, gradeSubmission] = useMutation(GradeSubmissionMutation);
  const [batching, setBatching] = useState(false);
  const [batchMsg, setBatchMsg] = useState<string | null>(null);

  const submissions: HomeworkSubmissionDetail[] =
    result.data?.homeworkAssignmentSubmissions ?? [];
  const aiSuggestions: AiBatchGradingItem[] =
    aiResult.data?.aiBatchGrading ?? [];

  // 统计
  const totalCount = submissions.length;
  const gradedCount = submissions.filter((s) => s.status === "GRADED").length;
  const submittedCount = submissions.filter(
    (s) => s.status === "SUBMITTED",
  ).length;

  /** 批量自动评分：触发 AI 建议查询（urql 响应式更新，建议加载后显示"应用 AI"按钮） */
  const handleBatchAutoGrade = () => {
    if (submissions.length === 0) return;
    setBatching(true);
    setBatchMsg(null);
    executeAi();
    setBatchMsg("AI 评分建议已生成，请逐份复核后点击「应用 AI」");
    setBatching(false);
  };

  /** 应用 AI 建议到单份提交 */
  const handleApplyAiSuggestion = async (
    sub: HomeworkSubmissionDetail,
  ) => {
    const suggestion = aiSuggestions.find(
      (a) => a.submissionId === sub.submissionId,
    );
    if (!suggestion) {
      setBatchMsg("未找到该提交的 AI 建议");
      return;
    }
    const res = await gradeSubmission({
      input: {
        submissionId: sub.submissionId,
        score: suggestion.suggestedScore,
        feedback: suggestion.suggestion,
        aiAssisted: true,
      },
    });
    if (res.error) {
      setBatchMsg(`保存失败：${res.error.message}`);
      return;
    }
    setBatchMsg(`已应用 AI 建议到 ${sub.studentName}`);
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href="/homework/submissions"
            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 HomeworkAssignmentSubmissionsQuery · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {/* 顶部统计 */}
      <section className="mb-8">
        <div className="grid grid-cols-3 gap-4 mb-4">
          <div className="p-4 border border-rule rounded-card">
            <p className="text-tiny uppercase tracking-wide text-ink-muted">
              已批改
            </p>
            <p className="mt-2 text-2xl font-serif text-success">
              {gradedCount}
            </p>
          </div>
          <div className="p-4 border border-rule rounded-card">
            <p className="text-tiny uppercase tracking-wide text-ink-muted">
              待批改
            </p>
            <p className="mt-2 text-2xl font-serif text-warning">
              {submittedCount}
            </p>
          </div>
          <div className="p-4 border border-rule rounded-card">
            <p className="text-tiny uppercase tracking-wide text-ink-muted">
              总提交
            </p>
            <p className="mt-2 text-2xl font-serif text-ink">{totalCount}</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={handleBatchAutoGrade}
            disabled={batching || submissions.length === 0}
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
          >
            {batching ? "生成中..." : "批量自动评分"}
          </button>
          {batchMsg && (
            <span className="text-tiny text-ink-muted">{batchMsg}</span>
          )}
        </div>
      </section>

      {result.fetching ? (
        <Loading lines={8} />
      ) : 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>
      ) : submissions.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-left text-tiny uppercase tracking-wide text-ink-muted w-24">
                    分数
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted w-24">
                    状态
                  </th>
                  <th className="px-4 py-3 text-right text-tiny uppercase tracking-wide text-ink-muted">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody>
                {submissions.map((sub) => {
                  const aiSuggestion = aiSuggestions.find(
                    (a) => a.submissionId === sub.submissionId,
                  );
                  return (
                    <tr key={sub.submissionId} className="border-t border-rule">
                      <td className="px-4 py-3 font-serif text-ink">
                        {sub.studentName}
                      </td>
                      <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                        {sub.studentNo}
                      </td>
                      <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                        {sub.submittedAt
                          ? new Date(sub.submittedAt).toLocaleString("zh-CN")
                          : "—"}
                      </td>
                      <td className="px-4 py-3 font-serif text-accent">
                        {sub.totalScore !== null ? sub.totalScore : "—"}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className="text-tiny"
                          style={{
                            color:
                              sub.status === "GRADED"
                                ? "var(--color-success)"
                                : "var(--color-warning)",
                          }}
                        >
                          {STATUS_LABEL[sub.status] ?? sub.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-3">
                          {aiSuggestion && sub.status === "SUBMITTED" && (
                            <button
                              type="button"
                              onClick={() => handleApplyAiSuggestion(sub)}
                              className="text-tiny uppercase tracking-wide text-warning hover:opacity-70"
                            >
                              应用 AI
                            </button>
                          )}
                          <Link
                            href={`/homework/submissions/${sub.submissionId}`}
                            className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                          >
                            批改
                          </Link>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </section>
      )}
    </div>
  );
}
