"use client";

/**
 * 扫描批改视图页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL SubmissionScanGradingQuery：按 submissionId 拉取扫描批改视图
 * - GraphQL SaveScanGradingMutation：保存扫描批改
 *
 * 布局：
 * - 顶部：学生信息 + 提交时间
 * - 左侧：扫描图片预览（可缩放 zoom in/out）
 * - 右侧：识别作答 + 评分表单（每题：题号 + 题干 + 已识别作答 + AI 评分建议 + 分数 input + 反馈 textarea）
 * - 底部："保存批改" 调用 SaveScanGradingMutation + "上一份"/"下一份" 导航
 *
 * 维护者：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 {
  SubmissionScanGradingQuery,
  SaveScanGradingMutation,
} from "@/lib/graphql-p7-advanced";
import type {
  SubmissionScanGrading,
  ScanGradingItem,
} from "@/lib/graphql-p7-advanced";

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

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

  const [result] = useQuery({
    query: SubmissionScanGradingQuery,
    variables: { submissionId },
    pause: !submissionId,
  });

  const [, saveGrading] = useMutation(SaveScanGradingMutation);

  const scan: SubmissionScanGrading | null =
    result.data?.submissionScanGrading ?? null;

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

  // 图片缩放状态
  const [zoom, setZoom] = useState(1);
  const [currentImageIdx, setCurrentImageIdx] = useState(0);

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

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

  /** 保存批改 */
  const handleSave = async () => {
    if (!scan) return;
    setSubmitting(true);
    setSaveError(null);
    setSaveMsg(null);
    const items = scan.items.map((item) => {
      const g = questionGrades[item.questionId];
      const score = Number(g?.score ?? "0");
      return {
        questionId: item.questionId,
        score: Number.isNaN(score) ? 0 : score,
        feedback: g?.feedback || null,
      };
    });
    const res = await saveGrading({
      input: { submissionId: scan.submissionId, items },
    });
    setSubmitting(false);
    if (res.error) {
      setSaveError(res.error.message);
      return;
    }
    setSaveMsg("已保存批改");
  };

  const images = scan?.images ?? [];
  const currentImage = images[currentImageIdx];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={`/homework/submissions/${submissionId}`}
            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 SubmissionScanGradingQuery + SaveScanGradingMutation · 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>
      ) : !scan ? (
        <Empty title="未找到扫描批改数据" description="该提交无扫描批改记录" />
      ) : (
        <>
          {/* 顶部：学生信息 + 提交时间 */}
          <section className="mb-8">
            <div className="flex items-baseline justify-between">
              <div>
                <h2 className="text-xl font-serif text-ink">
                  {scan.homeworkTitle}
                </h2>
                <p className="mt-2 text-sm text-ink-muted">
                  学生：
                  <span className="font-serif text-ink">
                    {scan.studentName}
                  </span>
                  <span className="mx-2" aria-hidden="true">·</span>
                  学号：
                  <span className="font-mono text-tiny">
                    {scan.studentNo}
                  </span>
                </p>
                <p className="mt-1 text-tiny text-ink-muted">
                  提交时间：
                  {new Date(scan.submittedAt).toLocaleString("zh-CN")}
                </p>
              </div>
              <div className="text-right">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  当前总分
                </span>
                <p className="text-2xl font-serif text-accent">
                  {computedTotal}
                </p>
              </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">
                扫描图片
                {images.length > 1 && (
                  <span className="ml-2 text-sm font-sans text-ink-muted">
                    第 {currentImageIdx + 1} / {images.length} 页
                  </span>
                )}
              </h3>
              <div className="rule-thin mb-4" />

              {images.length === 0 ? (
                <Empty title="无扫描图片" description="该提交无扫描图片" />
              ) : (
                <div>
                  {/* 图片预览区 */}
                  <div className="border border-rule rounded-card bg-subtle p-4 flex items-center justify-center overflow-hidden" style={{ minHeight: "400px" }}>
                    {currentImage && (
                      <img
                        src={currentImage.url}
                        alt={`扫描第 ${currentImage.page} 页`}
                        style={{ transform: `scale(${zoom})`, maxHeight: "380px", transition: "transform 0.2s" }}
                        className="max-w-full h-auto"
                      />
                    )}
                  </div>

                  {/* 缩放控制 + 翻页 */}
                  <div className="mt-4 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => setZoom((z) => Math.max(0.5, z - 0.1))}
                        className="px-2 py-1 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle"
                      >
                        缩小
                      </button>
                      <span className="text-tiny font-mono text-ink-muted">
                        {Math.round(zoom * 100)}%
                      </span>
                      <button
                        type="button"
                        onClick={() => setZoom((z) => Math.min(3, z + 0.1))}
                        className="px-2 py-1 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle"
                      >
                        放大
                      </button>
                    </div>
                    {images.length > 1 && (
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          onClick={() => setCurrentImageIdx((i) => Math.max(0, i - 1))}
                          disabled={currentImageIdx === 0}
                          className="px-2 py-1 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle disabled:opacity-50"
                        >
                          上一页
                        </button>
                        <button
                          type="button"
                          onClick={() => setCurrentImageIdx((i) => Math.min(images.length - 1, i + 1))}
                          disabled={currentImageIdx >= images.length - 1}
                          className="px-2 py-1 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle disabled:opacity-50"
                        >
                          下一页
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </section>

            {/* 右侧：识别作答 + 评分表单 */}
            <section>
              <h3 className="text-lg font-serif text-ink mb-4">识别作答 + 评分</h3>
              <div className="rule-thin mb-4" />

              <ul className="space-y-4 max-h-[600px] overflow-y-auto pr-2">
                {scan.items.map((item: ScanGradingItem, i) => {
                  const g = questionGrades[item.questionId];
                  return (
                    <li
                      key={item.questionId}
                      className="border border-rule rounded-card p-4"
                    >
                      <div className="flex items-baseline justify-between mb-2">
                        <h4 className="text-sm font-serif text-ink">
                          第 {i + 1} 题
                        </h4>
                        <span className="text-tiny text-ink-muted">
                          / {item.maxScore}
                        </span>
                      </div>
                      <p className="text-sm text-ink mb-3">
                        {item.questionTitle}
                      </p>

                      {/* 已识别作答（可编辑） */}
                      <div className="mb-3">
                        <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                          已识别作答
                        </label>
                        <textarea
                          value={g?.recognizedAnswer ?? ""}
                          onChange={(e) =>
                            setQuestionGrades((prev) => ({
                              ...prev,
                              [item.questionId]: {
                                score: g?.score ?? "",
                                feedback: g?.feedback ?? "",
                                recognizedAnswer: e.target.value,
                              },
                            }))
                          }
                          rows={2}
                          className="w-full px-2 py-1 bg-subtle border border-rule rounded-button text-sm text-ink focus:outline-none focus:border-accent"
                        />
                      </div>

                      {/* AI 评分建议 */}
                      {item.aiSuggestion && (
                        <div className="mb-3 p-2 border border-accent rounded-card bg-surface">
                          <p className="text-tiny uppercase tracking-wide text-accent mb-1">
                            AI 评分建议
                            <span className="ml-2 text-ink-muted">
                              建议 {item.aiSuggestedScore} 分
                            </span>
                          </p>
                          <p className="text-tiny text-ink">
                            {item.aiSuggestion}
                          </p>
                          <button
                            type="button"
                            onClick={() =>
                              setQuestionGrades((prev) => ({
                                ...prev,
                                [item.questionId]: {
                                  score: String(item.aiSuggestedScore ?? ""),
                                  feedback: g?.feedback ?? item.aiSuggestion ?? "",
                                  recognizedAnswer: g?.recognizedAnswer ?? "",
                                },
                              }))
                            }
                            className="mt-1 text-tiny text-accent hover:opacity-70"
                          >
                            采用建议
                          </button>
                        </div>
                      )}

                      {/* 分数 + 反馈 */}
                      <div className="grid grid-cols-3 gap-3">
                        <div>
                          <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                            分数
                          </label>
                          <input
                            type="number"
                            min={0}
                            max={item.maxScore}
                            value={g?.score ?? ""}
                            onChange={(e) =>
                              setQuestionGrades((prev) => ({
                                ...prev,
                                [item.questionId]: {
                                  score: e.target.value,
                                  feedback: g?.feedback ?? "",
                                  recognizedAnswer: g?.recognizedAnswer ?? "",
                                },
                              }))
                            }
                            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,
                                [item.questionId]: {
                                  score: g?.score ?? "",
                                  feedback: e.target.value,
                                  recognizedAnswer: g?.recognizedAnswer ?? "",
                                },
                              }))
                            }
                            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>
                    </li>
                  );
                })}
              </ul>

              {/* 保存按钮 */}
              <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>
              {scan.prevSubmissionId ? (
                <Link
                  href={`/homework/submissions/${scan.prevSubmissionId}/scan-grading`}
                  className="text-sm text-accent hover:opacity-70"
                >
                  ← 上一份
                </Link>
              ) : (
                <span className="text-sm text-ink-muted">已是第一份</span>
              )}
            </div>
            <div>
              {scan.nextSubmissionId ? (
                <Link
                  href={`/homework/submissions/${scan.nextSubmissionId}/scan-grading`}
                  className="text-sm text-accent hover:opacity-70"
                >
                  下一份 →
                </Link>
              ) : (
                <span className="text-sm text-ink-muted">已是最后一份</span>
              )}
            </div>
          </section>
        </>
      )}
    </div>
  );
}
