"use client";

/**
 * 监考面板页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ProctoringStatusQuery：按 examId 拉取监考状态（摘要 + 学生列表 + 近期事件）
 * - GraphQL ProctoringEventMutation：提交监考事件（WARNING/FLAG/NOTE）
 *
 * 布局：
 * - 顶部：标题 + "开始监考"/"结束监考" 按钮 + 手动刷新按钮
 * - 摘要卡片：应考数/在线数/已交卷数/异常数
 * - 左侧：学生状态列表（按状态筛选）
 * - 右侧：近期事件流（含操作按钮"标记"/"备注"）
 *
 * 维护者：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 {
  ProctoringStatusQuery,
  ProctoringEventMutation,
} from "@/lib/graphql-p7-advanced";
import type {
  ProctoringStudent,
  ProctoringEvent,
  ProctoringStudentStatus,
} from "@/lib/graphql-p7-advanced";

/** 学生状态中文映射 */
const STUDENT_STATUS_LABEL: Record<ProctoringStudentStatus, string> = {
  online: "在线",
  offline: "离线",
  submitted: "已交卷",
  flagged: "异常",
};

/** 学生状态对应颜色 */
function studentStatusColor(status: ProctoringStudentStatus): string {
  switch (status) {
    case "online":
      return "var(--color-success)";
    case "submitted":
      return "var(--color-ink-muted)";
    case "flagged":
      return "var(--color-danger)";
    default:
      return "var(--color-warning)";
  }
}

/** 事件类型中文映射 */
const EVENT_TYPE_LABEL: Record<string, string> = {
  WARNING: "警告",
  FLAG: "标记",
  NOTE: "备注",
};

/** 事件类型颜色 */
function eventTypeColor(type: string): string {
  switch (type) {
    case "WARNING":
      return "var(--color-warning)";
    case "FLAG":
      return "var(--color-danger)";
    case "NOTE":
      return "var(--color-ink-muted)";
    default:
      return "var(--color-ink-muted)";
  }
}

/** 状态筛选选项 */
const STATUS_FILTER_OPTIONS: Array<{ value: string; label: string }> = [
  { value: "", label: "全部状态" },
  { value: "online", label: "在线" },
  { value: "offline", label: "离线" },
  { value: "submitted", label: "已交卷" },
  { value: "flagged", label: "异常" },
];

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

  const [result, reexecuteQuery] = useQuery({
    query: ProctoringStatusQuery,
    variables: { examId },
    pause: !examId,
    requestPolicy: "network-only",
  });

  const [, submitEvent] = useMutation(ProctoringEventMutation);

  const [statusFilter, setStatusFilter] = useState("");
  const [actionMsg, setActionMsg] = useState<string | null>(null);
  const [proctoringActive, setProctoringActive] = useState(false);

  const status = result.data?.proctoringStatus;
  const summary = status?.summary;
  const allStudents: ProctoringStudent[] = status?.students ?? [];
  const recentEvents: ProctoringEvent[] = status?.recentEvents ?? [];

  // 按状态筛选学生
  const filteredStudents = statusFilter
    ? allStudents.filter((s) => s.status === statusFilter)
    : allStudents;

  /** 提交监考事件 */
  const handleEvent = async (
    studentId: string,
    eventType: "WARNING" | "FLAG" | "NOTE",
    note?: string,
  ) => {
    setActionMsg(null);
    const res = await submitEvent({
      input: {
        examId,
        studentId,
        eventType,
        note: note ?? null,
      },
    });
    if (res.error) {
      setActionMsg(`操作失败：${res.error.message}`);
      return;
    }
    setActionMsg("已提交事件");
    // 刷新数据
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  /** 手动刷新 */
  const handleRefresh = () => {
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  /** 开始/结束监考（mock：本地状态切换） */
  const toggleProctoring = () => {
    setProctoringActive((prev) => !prev);
    handleRefresh();
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={`/exams/${examId}`}
            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 ProctoringStatusQuery + ProctoringEventMutation · 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>
      ) : !status || !summary ? (
        <Empty title="未找到监考数据" description="该考试无监考信息" />
      ) : (
        <section className="space-y-8">
          {/* 顶部操作栏 */}
          <div className="flex items-center justify-between">
            <div>
              {summary.startedAt && (
                <p className="text-tiny text-ink-muted">
                  监考开始：
                  {new Date(summary.startedAt).toLocaleString("zh-CN")}
                </p>
              )}
            </div>
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={handleRefresh}
                className="px-3 py-1.5 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle"
              >
                刷新
              </button>
              <button
                type="button"
                onClick={toggleProctoring}
                className={
                  proctoringActive
                    ? "px-4 py-2 text-sm text-ink-on-accent bg-danger rounded-button hover:opacity-90"
                    : "px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
                }
              >
                {proctoringActive ? "结束监考" : "开始监考"}
              </button>
            </div>
          </div>

          {/* 摘要卡片 */}
          <div className="grid grid-cols-4 gap-4">
            <SummaryCard
              label="应考数"
              value={summary.expectedCount}
              color="var(--color-ink)"
            />
            <SummaryCard
              label="在线数"
              value={summary.onlineCount}
              color="var(--color-success)"
            />
            <SummaryCard
              label="已交卷"
              value={summary.submittedCount}
              color="var(--color-ink-muted)"
            />
            <SummaryCard
              label="异常数"
              value={summary.flaggedCount}
              color="var(--color-danger)"
            />
          </div>

          {actionMsg && (
            <p className="text-tiny text-success">{actionMsg}</p>
          )}

          {/* 左右分栏：学生列表 + 事件流 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* 左侧：学生状态列表 */}
            <section>
              <div className="flex items-baseline justify-between mb-4">
                <h3 className="text-lg font-serif text-ink">学生状态</h3>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-2 py-1 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
                >
                  {STATUS_FILTER_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
              <div className="rule-thin mb-4" />

              {filteredStudents.length === 0 ? (
                <Empty title="暂无学生" description="当前筛选无学生记录" />
              ) : (
                <ul className="space-y-2 max-h-[600px] overflow-y-auto">
                  {filteredStudents.map((stu) => (
                    <li
                      key={stu.studentId}
                      className="flex items-center justify-between p-3 border border-rule rounded-card hover:bg-subtle"
                    >
                      <div>
                        <p className="text-sm font-serif text-ink">
                          {stu.studentName}
                          <span className="ml-2 text-tiny font-mono text-ink-muted">
                            {stu.studentNo}
                          </span>
                        </p>
                        {stu.lastEventAt && (
                          <p className="mt-1 text-tiny text-ink-muted">
                            最近事件：
                            {new Date(stu.lastEventAt).toLocaleTimeString("zh-CN")}
                          </p>
                        )}
                      </div>
                      <div className="flex items-center gap-3">
                        <span
                          className="text-tiny"
                          style={{ color: studentStatusColor(stu.status) }}
                        >
                          {STUDENT_STATUS_LABEL[stu.status]}
                        </span>
                        <div className="flex gap-1">
                          <button
                            type="button"
                            onClick={() =>
                              handleEvent(stu.studentId, "FLAG", "教师标记异常")
                            }
                            className="px-2 py-0.5 text-tiny text-danger bg-transparent border border-danger rounded-button hover:bg-subtle"
                          >
                            标记
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              const note = window.prompt("输入备注：");
                              if (note) handleEvent(stu.studentId, "NOTE", note);
                            }}
                            className="px-2 py-0.5 text-tiny text-ink bg-transparent border border-rule rounded-button hover:bg-subtle"
                          >
                            备注
                          </button>
                        </div>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            {/* 右侧：事件流 */}
            <section>
              <h3 className="text-lg font-serif text-ink mb-4">近期事件</h3>
              <div className="rule-thin mb-4" />

              {recentEvents.length === 0 ? (
                <Empty title="暂无事件" description="监考期间无事件记录" />
              ) : (
                <ul className="space-y-3 max-h-[600px] overflow-y-auto">
                  {recentEvents.map((evt) => (
                    <li
                      key={evt.eventId}
                      className="p-3 border border-rule rounded-card"
                    >
                      <div className="flex items-baseline justify-between mb-1">
                        <span
                          className="text-tiny font-serif"
                          style={{ color: eventTypeColor(evt.eventType) }}
                        >
                          {EVENT_TYPE_LABEL[evt.eventType] ?? evt.eventType}
                        </span>
                        <span className="text-tiny text-ink-muted">
                          {new Date(evt.createdAt).toLocaleString("zh-CN")}
                        </span>
                      </div>
                      <p className="text-sm text-ink">
                        <span className="font-serif">{evt.studentName}</span>
                        <span className="ml-2 text-tiny font-mono text-ink-muted">
                          {evt.studentNo}
                        </span>
                      </p>
                      {evt.note && (
                        <p className="mt-1 text-sm text-ink-muted">
                          {evt.note}
                        </p>
                      )}
                    </li>
                  ))}
                </ul>
              )}
            </section>
          </div>
        </section>
      )}
    </div>
  );
}

/** 摘要卡片子组件 */
function SummaryCard({
  label,
  value,
  color,
}: {
  label: string;
  value: number;
  color: string;
}): React.ReactNode {
  return (
    <div className="p-4 border border-rule rounded-card bg-surface">
      <p className="text-tiny uppercase tracking-wide text-ink-muted">
        {label}
      </p>
      <p
        className="mt-2 text-3xl font-serif"
        style={{ color }}
      >
        {value}
      </p>
    </div>
  );
}
