"use client";

/**
 * 单份提交批改页（核心）
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL HomeworkAssignmentSubmissionsQuery：按作业 ID 拉取所有提交（用于定位当前 + 上一份/下一份）
 * - GraphQL GradeSubmissionMutation：保存批改
 *
 * 布局：
 * - 顶部：学生信息 + 提交时间 + 状态
 * - 左侧：题目作答展示（题干 + 学生作答 + 正确答案）
 * - 右侧：评分表单（每题分数 + 反馈 + AI 评分建议按钮）
 * - 底部：上一份/下一份导航
 *
 * AI 辅助按钮：mock 流式返回评分建议（逐字显示，setInterval 模拟 SSE）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useEffect, useMemo } 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 } from "@/lib/graphql-p7-grades";
import { GradeSubmissionMutation } from "@/lib/graphql-p7-grades";
import type { HomeworkSubmissionDetail, SubmissionAnswer } from "@/lib/graphql-p7-grades";

/** 题型中文映射 */
const QUESTION_TYPE_LABEL: Record<string, string> = {
  SINGLE_CHOICE: "单选题",
  MULTIPLE_CHOICE: "多选题",
  SHORT_ANSWER: "简答题",
  ESSAY: "论述题",
};

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

/** 每题评分表单状态 */
interface QuestionGrade {
  score: string;
  feedback: string;
}

/** 从 submissionId 解析 homeworkId（规约：${homeworkId}-sub-XXX） */
function parseHomeworkId(submissionId: string): string {
  const match = submissionId.match(/^(.+)-sub-\d+$/);
  return match?.[1] ?? "";
}

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

  // 拉取该作业所有提交（用于定位当前 + 导航）
  const [result, reexecuteQuery] = useQuery({
    query: HomeworkAssignmentSubmissionsQuery,
    variables: { homeworkId },
    pause: !homeworkId,
  });

  const [, gradeSubmission] = useMutation(GradeSubmissionMutation);

  const allSubmissions: HomeworkSubmissionDetail[] =
    result.data?.homeworkAssignmentSubmissions ?? [];

  // 定位当前提交 + 前后导航
  const currentIndex = allSubmissions.findIndex(
    (s) => s.submissionId === submissionId,
  );
  const submission: HomeworkSubmissionDetail | undefined =
    currentIndex >= 0 ? allSubmissions[currentIndex] : undefined;
  const prevSubmission =
    currentIndex > 0 ? allSubmissions[currentIndex - 1] : null;
  const nextSubmission =
    currentIndex >= 0 && currentIndex < allSubmissions.length - 1
      ? allSubmissions[currentIndex + 1] ?? null
      : null;

  // 每题评分状态
  const [questionGrades, setQuestionGrades] = useState<
    Record<string, QuestionGrade>
  >({});
  const [totalFeedback, setTotalFeedback] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [saveMsg, setSaveMsg] = useState<string | null>(null);
  const [saveError, setSaveError] = useState<string | null>(null);

  // AI 流式建议状态：按 questionId 索引
  const [aiStreaming, setAiStreaming] = useState<Record<string, string>>({});
  const [aiLoading, setAiLoading] = useState<string | null>(null);

  // 当 submission 变化时，初始化评分表单
  useEffect(() => {
    if (!submission) return;
    const next: Record<string, QuestionGrade> = {};
    submission.answers.forEach((a) => {
      next[a.questionId] = {
        score: a.score?.toString() ?? "",
        feedback: a.feedback ?? "",
      };
    });
    setQuestionGrades(next);
    setTotalFeedback(submission.answers[0]?.feedback ?? "");
    setSaveMsg(null);
    setSaveError(null);
    setAiStreaming({});
  }, [submission]);

  // 计算当前总分（实时）
  const computedTotal = useMemo(() => {
    let total = 0;
    submission?.answers.forEach((a) => {
      const g = questionGrades[a.questionId];
      if (g && g.score !== "") {
        const n = Number(g.score);
        if (!Number.isNaN(n)) total += n;
      }
    });
    return total;
  }, [submission, questionGrades]);

  /** 保存批改 */
  const handleSave = async () => {
    if (!submission) return;
    setSubmitting(true);
    setSaveError(null);
    setSaveMsg(null);
    const questionScores = submission.answers.map((a) => {
      const g = questionGrades[a.questionId];
      const score = Number(g?.score ?? "0");
      return {
        questionId: a.questionId,
        score: Number.isNaN(score) ? 0 : score,
        feedback: g?.feedback || null,
      };
    });
    const res = await gradeSubmission({
      input: {
        submissionId: submission.submissionId,
        score: computedTotal,
        feedback: totalFeedback.trim() || null,
        aiAssisted: Object.keys(aiStreaming).length > 0,
        questionScores,
      },
    });
    setSubmitting(false);
    if (res.error) {
      setSaveError(res.error.message);
      return;
    }
    setSaveMsg("已保存批改");
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  /** AI 评分建议（mock SSE 流式：逐字显示） */
  const handleAiSuggest = (answer: SubmissionAnswer) => {
    if (!answer.aiSuggestion) return;
    setAiLoading(answer.questionId);
    const full = answer.aiSuggestion;
    let i = 0;
    const timer = setInterval(() => {
      i += 2;
      setAiStreaming((prev) => ({
        ...prev,
        [answer.questionId]: full.slice(0, i),
      }));
      if (i >= full.length) {
        clearInterval(timer);
        setAiLoading(null);
        // 自动填充建议分数（maxScore 的 80%）
        setQuestionGrades((prev) => ({
          ...prev,
          [answer.questionId]: {
            score: Math.round(answer.maxScore * 0.8).toString(),
            feedback: full,
          },
        }));
      }
    }, 30);
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={
              homeworkId
                ? `/homework/assignments/${homeworkId}/submissions`
                : "/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 + GradeSubmissionMutation · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {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>
      ) : !submission ? (
        <Empty title="未找到提交" description="该提交不存在或已被删除" />
      ) : (
        <>
          {/* 顶部：学生信息 + 提交时间 + 状态 */}
          <section className="mb-8">
            <div className="flex items-baseline justify-between">
              <div>
                <h2 className="text-xl font-serif text-ink">
                  {submission.homeworkTitle}
                </h2>
                <p className="mt-2 text-sm text-ink-muted">
                  学生：
                  <span className="font-serif text-ink">
                    {submission.studentName}
                  </span>
                  <span className="mx-2" aria-hidden="true">
                    ·
                  </span>
                  学号：
                  <span className="font-mono text-tiny">
                    {submission.studentNo}
                  </span>
                </p>
                <p className="mt-1 text-tiny text-ink-muted">
                  提交时间：
                  {submission.submittedAt
                    ? new Date(submission.submittedAt).toLocaleString("zh-CN")
                    : "—"}
                </p>
              </div>
              <div className="text-right">
                <span
                  className="text-tiny"
                  style={{
                    color:
                      submission.status === "GRADED"
                        ? "var(--color-success)"
                        : "var(--color-warning)",
                  }}
                >
                  {STATUS_LABEL[submission.status] ?? submission.status}
                </span>
              </div>
            </div>
          </section>

          {/* 左右分栏：作答展示 + 评分表单 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            {/* 左侧：题目作答展示 */}
            <section>
              <h3 className="text-lg font-serif text-ink mb-4">题目作答</h3>
              <div className="rule-thin mb-4" />
              <ul className="space-y-6">
                {submission.answers.map((answer, i) => {
                  const aiText = aiStreaming[answer.questionId];
                  const isAiLoading = aiLoading === answer.questionId;
                  return (
                    <li
                      key={answer.questionId}
                      className="border border-rule rounded-card p-4"
                    >
                      <div className="flex items-baseline justify-between mb-3">
                        <h4 className="text-base font-serif text-ink">
                          第 {i + 1} 题 ·{" "}
                          {QUESTION_TYPE_LABEL[answer.questionType] ??
                            answer.questionType}
                        </h4>
                        <span className="text-tiny text-ink-muted">
                          满分 {answer.maxScore}
                        </span>
                      </div>
                      <p className="text-sm text-ink mb-3">
                        {answer.questionTitle}
                      </p>
                      <div className="space-y-2 text-sm">
                        <div>
                          <span className="text-tiny uppercase tracking-wide text-ink-muted">
                            学生作答
                          </span>
                          <p className="mt-1 text-ink p-2 bg-subtle rounded-button">
                            {answer.studentAnswer}
                          </p>
                        </div>
                        <div>
                          <span className="text-tiny uppercase tracking-wide text-ink-muted">
                            正确答案
                          </span>
                          <p className="mt-1 text-success p-2 bg-surface rounded-button border border-rule">
                            {answer.correctAnswer}
                          </p>
                        </div>
                      </div>
                      {/* AI 流式建议展示 */}
                      {aiText !== undefined && (
                        <div className="mt-3 p-3 border border-accent rounded-card bg-surface">
                          <p className="text-tiny uppercase tracking-wide text-accent mb-1">
                            AI 评分建议
                            {isAiLoading && (
                              <span className="ml-2 animate-pulse">▋</span>
                            )}
                          </p>
                          <p className="text-sm text-ink">{aiText}</p>
                        </div>
                      )}
                    </li>
                  );
                })}
              </ul>
            </section>

            {/* 右侧：评分表单 */}
            <section>
              <h3 className="text-lg font-serif text-ink mb-4">评分表单</h3>
              <div className="rule-thin mb-4" />
              <ul className="space-y-6">
                {submission.answers.map((answer, i) => {
                  const g = questionGrades[answer.questionId];
                  const aiText = aiStreaming[answer.questionId];
                  return (
                    <li
                      key={answer.questionId}
                      className="border border-rule rounded-card p-4"
                    >
                      <div className="flex items-baseline justify-between mb-3">
                        <h4 className="text-sm font-serif text-ink">
                          第 {i + 1} 题评分
                        </h4>
                        <span className="text-tiny text-ink-muted">
                          / {answer.maxScore}
                        </span>
                      </div>
                      <div className="grid grid-cols-3 gap-3 mb-3">
                        <div>
                          <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                            分数
                          </label>
                          <input
                            type="number"
                            min={0}
                            max={answer.maxScore}
                            value={g?.score ?? ""}
                            onChange={(e) =>
                              setQuestionGrades((prev) => ({
                                ...prev,
                                [answer.questionId]: {
                                  score: e.target.value,
                                  feedback: g?.feedback ?? "",
                                },
                              }))
                            }
                            className="w-full px-2 py-1 bg-paper border border-rule rounded-button text-sm text-ink focus:outline-none focus:border-accent"
                            placeholder="0"
                          />
                        </div>
                        <div className="col-span-2">
                          <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                            反馈
                          </label>
                          <input
                            type="text"
                            value={g?.feedback ?? ""}
                            onChange={(e) =>
                              setQuestionGrades((prev) => ({
                                ...prev,
                                [answer.questionId]: {
                                  score: g?.score ?? "",
                                  feedback: e.target.value,
                                },
                              }))
                            }
                            className="w-full px-2 py-1 bg-paper border border-rule rounded-button text-sm text-ink focus:outline-none focus:border-accent"
                            placeholder="可选：本题反馈"
                          />
                        </div>
                      </div>
                      {answer.aiSuggestion && aiText === undefined && (
                        <button
                          type="button"
                          onClick={() => handleAiSuggest(answer)}
                          className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                        >
                          AI 评分建议
                        </button>
                      )}
                    </li>
                  );
                })}
              </ul>

              {/* 总分 + 总反馈 */}
              <div className="mt-6 p-4 border border-rule rounded-card bg-subtle">
                <div className="flex items-baseline justify-between mb-3">
                  <span className="text-tiny uppercase tracking-wide text-ink-muted">
                    总分
                  </span>
                  <span className="text-2xl font-serif text-accent">
                    {computedTotal}
                  </span>
                </div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  总体反馈
                </label>
                <textarea
                  value={totalFeedback}
                  onChange={(e) => setTotalFeedback(e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 bg-paper border border-rule rounded-button text-sm text-ink focus:outline-none focus:border-accent"
                  placeholder="可选：总体评语"
                />
              </div>

              {/* 保存按钮 */}
              <div className="mt-4 flex items-center gap-3">
                <button
                  type="button"
                  onClick={handleSave}
                  disabled={submitting}
                  className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
                >
                  {submitting ? "保存中..." : "保存批改"}
                </button>
                {saveMsg && (
                  <span className="text-tiny text-success">{saveMsg}</span>
                )}
                {saveError && (
                  <span className="text-tiny text-danger">{saveError}</span>
                )}
              </div>
            </section>
          </div>

          {/* 底部：上一份/下一份导航 */}
          <section className="border-t border-rule pt-6 flex items-baseline justify-between">
            <div>
              {prevSubmission ? (
                <Link
                  href={`/homework/submissions/${prevSubmission.submissionId}`}
                  className="text-sm text-accent hover:opacity-70"
                >
                  ← 上一份（{prevSubmission.studentName}）
                </Link>
              ) : (
                <span className="text-sm text-ink-muted">已是第一份</span>
              )}
            </div>
            <span className="text-tiny font-mono text-ink-muted">
              {currentIndex + 1} / {allSubmissions.length}
            </span>
            <div>
              {nextSubmission ? (
                <Link
                  href={`/homework/submissions/${nextSubmission.submissionId}`}
                  className="text-sm text-accent hover:opacity-70"
                >
                  下一份（{nextSubmission.studentName}） →
                </Link>
              ) : (
                <span className="text-sm text-ink-muted">已是最后一份</span>
              )}
            </div>
          </section>
        </>
      )}
    </div>
  );
}
