"use client";

/**
 * 作业详情页 + 批改界面
 *
 * 数据来源（contract.md §2.4）：
 * - GraphQL HomeworkDetailQuery（P3 扩展，MSW mock）获取作业详情 + 提交列表
 * - GraphQL RecordGradeMutation（P3 扩展，MSW mock）录入批改分数
 * - 动态路由 /homework/[id]
 *
 * 维护者：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 { HomeworkDetailQuery, RecordGradeMutation } from "@/lib/graphql";
import type { HomeworkSubmission } from "@/lib/graphql";

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

interface GradingFormState {
  [submissionId: string]: {
    score: string;
    feedback: string;
  };
}

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

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

  const [recordGradeResult, recordGrade] = useMutation(RecordGradeMutation);

  // 批改表单状态：按 submissionId 索引
  const [gradingForms, setGradingForms] = useState<GradingFormState>({});
  const [activeSubmissionId, setActiveSubmissionId] = useState<string | null>(
    null,
  );
  const [submittingId, setSubmittingId] = useState<string | null>(null);
  const [errorId, setErrorId] = useState<string | null>(null);

  const openGradingForm = (sub: HomeworkSubmission) => {
    setActiveSubmissionId(sub.id);
    setGradingForms((prev) => ({
      ...prev,
      [sub.id]: {
        score: sub.score?.toString() ?? "",
        feedback: sub.feedback ?? "",
      },
    }));
  };

  const closeGradingForm = () => {
    setActiveSubmissionId(null);
  };

  const handleRecordGrade = async (sub: HomeworkSubmission) => {
    const form = gradingForms[sub.id];
    if (!form) return;
    const score = Number(form.score);
    if (Number.isNaN(score)) {
      setErrorId(sub.id);
      return;
    }
    setSubmittingId(sub.id);
    setErrorId(null);
    // 乐观更新：本地表单先展示新值；失败回滚由错误信息提示
    const res = await recordGrade({
      input: {
        studentId: sub.studentId,
        homeworkId: homeworkId,
        score,
        feedback: form.feedback.trim() || null,
      },
    });
    setSubmittingId(null);
    if (res.error) {
      setErrorId(sub.id);
      return;
    }
    // 成功后重新拉取详情刷新提交列表
    reexecuteQuery({ requestPolicy: "network-only" });
    closeGradingForm();
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={`/homework?classId=${result.data?.homeworkDetail?.classId ?? ""}`}
            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 HomeworkDetailQuery · core-edu 域（P3 扩展，MSW mock）
        </p>
      </header>

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

      {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>
      ) : !result.data?.homeworkDetail ? (
        <Empty title="未找到作业" description="该作业不存在或已被删除" />
      ) : (
        <section className="max-w-4xl">
          {/* 基本信息 */}
          <div className="mb-10">
            <h2 className="text-xl font-serif text-ink mb-2">
              {result.data.homeworkDetail.title}
            </h2>
            {result.data.homeworkDetail.description && (
              <p className="mt-1 text-sm text-ink-muted">
                {result.data.homeworkDetail.description}
              </p>
            )}
            <div className="rule-thin mb-4 mt-3" />
            <dl className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  截止时间
                </dt>
                <dd className="mt-1 text-ink">
                  {new Date(result.data.homeworkDetail.dueDate).toLocaleString("zh-CN")}
                </dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  状态
                </dt>
                <dd className="mt-1 text-ink">
                  {SUBMISSION_STATUS_LABEL[result.data.homeworkDetail.status] ?? result.data.homeworkDetail.status}
                </dd>
              </div>
            </dl>
          </div>

          {/* 学生提交列表 */}
          <div>
            <div className="flex items-baseline justify-between mb-4">
              <h3 className="text-xl font-serif text-ink">
                学生提交
                <span className="ml-2 text-sm font-sans text-ink-muted">
                  {result.data.homeworkDetail.submissions.length} 份
                </span>
              </h3>
            </div>
            <div className="rule-thin mb-6" />

            {result.data.homeworkDetail.submissions.length === 0 ? (
              <Empty title="暂无提交" description="学生尚未提交作业" />
            ) : (
              <ul className="space-y-0">
                {result.data.homeworkDetail.submissions.map(
                  (sub: HomeworkSubmission) => {
                    const isActive = activeSubmissionId === sub.id;
                    const form = gradingForms[sub.id];
                    const hasError = errorId === sub.id;
                    return (
                      <li
                        key={sub.id}
                        className="py-4 border-b border-rule"
                      >
                        <div className="grid grid-cols-12 gap-4 items-baseline">
                          <div className="col-span-5">
                            <h4 className="text-base font-serif text-ink">
                              {sub.studentName}
                            </h4>
                            <p className="mt-1 text-tiny text-ink-muted">
                              学生 ID: {sub.studentId}
                            </p>
                            {sub.submittedAt && (
                              <p className="mt-1 text-tiny text-ink-muted">
                                提交时间：
                                {new Date(sub.submittedAt).toLocaleString("zh-CN")}
                              </p>
                            )}
                          </div>
                          <div className="col-span-2 text-sm text-ink">
                            {sub.score !== null ? `${sub.score} 分` : "—"}
                          </div>
                          <div className="col-span-2 text-tiny text-ink-muted">
                            {SUBMISSION_STATUS_LABEL[sub.status] ?? sub.status}
                          </div>
                          <div className="col-span-3 text-right">
                            {sub.status !== "NOT_SUBMITTED" && (
                              <button
                                type="button"
                                onClick={() =>
                                  isActive
                                    ? closeGradingForm()
                                    : openGradingForm(sub)
                                }
                                className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                              >
                                {isActive ? "收起" : "批改"}
                              </button>
                            )}
                          </div>
                        </div>

                        {/* 已有反馈展示 */}
                        {sub.feedback && !isActive && (
                          <p className="mt-2 text-sm text-ink-muted pl-1">
                            反馈：{sub.feedback}
                          </p>
                        )}

                        {/* 批改表单 */}
                        {isActive && form && (
                          <div className="mt-4 p-4 border border-rule rounded-card bg-subtle">
                            <div className="grid grid-cols-3 gap-4 mb-3">
                              <div>
                                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                                  分数 <span className="text-danger">*</span>
                                </label>
                                <input
                                  type="number"
                                  min={0}
                                  value={form.score}
                                  onChange={(e) =>
                                    setGradingForms((prev) => ({
                                      ...prev,
                                      [sub.id]: {
                                        ...form,
                                        score: e.target.value,
                                      },
                                    }))
                                  }
                                  className="w-full px-3 py-2 bg-paper border border-rule rounded-button text-sm text-ink focus:outline-none"
                                  placeholder="0-100"
                                />
                              </div>
                              <div className="col-span-2">
                                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                                  反馈
                                </label>
                                <input
                                  type="text"
                                  value={form.feedback}
                                  onChange={(e) =>
                                    setGradingForms((prev) => ({
                                      ...prev,
                                      [sub.id]: {
                                        ...form,
                                        feedback: e.target.value,
                                      },
                                    }))
                                  }
                                  className="w-full px-3 py-2 bg-paper border border-rule rounded-button text-sm text-ink focus:outline-none"
                                  placeholder="可选：批改意见"
                                />
                              </div>
                            </div>
                            {hasError && (
                              <p className="text-tiny text-danger mb-2">
                                {recordGradeResult.error?.message ?? "录入失败"}
                              </p>
                            )}
                            <div className="flex items-center gap-3">
                              <button
                                type="button"
                                onClick={() => handleRecordGrade(sub)}
                                disabled={submittingId === sub.id}
                                className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
                              >
                                {submittingId === sub.id
                                  ? "录入中..."
                                  : "保存批改"}
                              </button>
                              <button
                                type="button"
                                onClick={closeGradingForm}
                                className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
                              >
                                取消
                              </button>
                              {recordGradeResult.data && !hasError && submittingId === null && (
                                <span className="text-tiny text-success">已保存</span>
                              )}
                            </div>
                          </div>
                        )}
                      </li>
                    );
                  },
                )}
              </ul>
            )}
          </div>
        </section>
      )}
    </div>
  );
}
