"use client";

/**
 * AI 辅助出题页面（P5）
 *
 * 数据来源（02-architecture-design.md §6 AI 辅助）：
 * - GraphQL GenerateQuestionMutation
 *
 * 功能：
 * - 表单：科目 / 题型 / 难度 / 知识点 / 题目数量
 * - 生成题目（mutation）+ SSE 流式效果模拟（setInterval 逐字显示）
 * - 完整题目展示（含选项、答案、解析）
 * - 复制到剪贴板 / 再生成一组
 * - 生成历史（本次会话内）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useEffect, useRef, useState } from "react";
import { useMutation } from "urql";
import { GenerateQuestionMutation } from "@/lib/graphql-p5";
import type { GeneratedQuestion, GenerateQuestionInput } from "@/lib/graphql-p5";

const SUBJECTS = ["数学", "语文", "英语", "物理", "化学"];
const QUESTION_TYPES = ["选择题", "填空题", "解答题"];
const DIFFICULTIES = ["简单", "中等", "困难"];

const STREAM_INTERVAL_MS = 25;

function buildQuestionText(q: GeneratedQuestion): string {
  return [
    q.question,
    "",
    ...q.options,
    "",
    `答案：${q.answer}`,
    "",
    `解析：${q.explanation}`,
  ].join("\n");
}

export default function AiAssistPage(): JSX.Element {
  const [subject, setSubject] = useState<string>(SUBJECTS[0] ?? "数学");
  const [questionType, setQuestionType] = useState<string>(
    QUESTION_TYPES[0] ?? "选择题",
  );
  const [difficulty, setDifficulty] = useState<string>(DIFFICULTIES[1] ?? "中等");
  const [knowledgePoints, setKnowledgePoints] = useState("导数应用");
  const [count, setCount] = useState(1);

  const [isGenerating, setIsGenerating] = useState(false);
  const [isStreaming, setIsStreaming] = useState(false);
  const [streamingText, setStreamingText] = useState("");
  const [generated, setGenerated] = useState<GeneratedQuestion | null>(null);
  const [history, setHistory] = useState<GeneratedQuestion[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const streamTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const [, generateQuestion] = useMutation(GenerateQuestionMutation);

  useEffect(() => {
    return () => {
      if (streamTimerRef.current) clearInterval(streamTimerRef.current);
    };
  }, []);

  const handleGenerate = async (): Promise<void> => {
    if (isGenerating || isStreaming) return;
    setIsGenerating(true);
    setError(null);
    setGenerated(null);
    setStreamingText("");
    setCopied(false);

    const input: GenerateQuestionInput = {
      subject,
      questionType,
      difficulty,
      knowledgePoints,
      count,
    };

    const res = await generateQuestion({ input });
    setIsGenerating(false);

    if (res.error || !res.data?.generateQuestion) {
      setError(res.error?.message ?? "生成失败，请重试");
      return;
    }

    const q = res.data.generateQuestion as GeneratedQuestion;
    const full = q.question;

    setIsStreaming(true);
    let i = 0;
    streamTimerRef.current = setInterval(() => {
      i += 1;
      setStreamingText(full.slice(0, i));
      if (i >= full.length) {
        if (streamTimerRef.current) {
          clearInterval(streamTimerRef.current);
          streamTimerRef.current = null;
        }
        setIsStreaming(false);
        setGenerated(q);
        setHistory((prev) => [q, ...prev].slice(0, 20));
      }
    }, STREAM_INTERVAL_MS);
  };

  const handleCopy = (): void => {
    if (!generated) return;
    const text = buildQuestionText(generated);
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      void navigator.clipboard.writeText(text).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      });
    }
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">AI 辅助出题</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL GenerateQuestionMutation · SSE 流式输出模拟（P5）
        </p>
      </header>

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

      {/* 生成表单 */}
      <section className="mb-8 max-w-3xl">
        <h2 className="text-xl font-serif text-ink mb-4">出题参数</h2>
        <div className="grid grid-cols-2 gap-4">
          <label className="flex flex-col gap-1">
            <span className="text-tiny uppercase tracking-wide text-ink-muted">
              科目
            </span>
            <select
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
            >
              {SUBJECTS.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-tiny uppercase tracking-wide text-ink-muted">
              题目类型
            </span>
            <select
              value={questionType}
              onChange={(e) => setQuestionType(e.target.value)}
              className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
            >
              {QUESTION_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-tiny uppercase tracking-wide text-ink-muted">
              难度等级
            </span>
            <select
              value={difficulty}
              onChange={(e) => setDifficulty(e.target.value)}
              className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
            >
              {DIFFICULTIES.map((d) => (
                <option key={d} value={d}>
                  {d}
                </option>
              ))}
            </select>
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-tiny uppercase tracking-wide text-ink-muted">
              题目数量
            </span>
            <input
              type="number"
              min={1}
              max={10}
              value={count}
              onChange={(e) => setCount(Number(e.target.value) || 1)}
              className="px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink"
            />
          </label>
          <label className="col-span-2 flex flex-col gap-1">
            <span className="text-tiny uppercase tracking-wide text-ink-muted">
              知识点
            </span>
            <input
              type="text"
              value={knowledgePoints}
              onChange={(e) => setKnowledgePoints(e.target.value)}
              className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
              placeholder="例如：导数应用、极值判定"
            />
          </label>
        </div>

        <div className="mt-6 flex items-center gap-4">
          <button
            type="button"
            onClick={handleGenerate}
            disabled={isGenerating || isStreaming}
            className="px-5 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isGenerating ? "生成中…" : "生成题目"}
          </button>
          {generated && !isStreaming && (
            <button
              type="button"
              onClick={handleGenerate}
              disabled={isGenerating || isStreaming}
              className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
            >
              再生成一组
            </button>
          )}
        </div>
      </section>

      {error && (
        <div className="mark-left mb-6 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">{error}</p>
        </div>
      )}

      {/* 生成结果（流式 + 完整） */}
      {(isGenerating || isStreaming || streamingText || generated) && (
        <section className="mb-10">
          <div className="flex items-baseline justify-between mb-4">
            <h2 className="text-xl font-serif text-ink">
              生成结果
              {isGenerating && (
                <span className="ml-3 text-sm font-sans text-ink-muted">
                  正在请求 AI…
                </span>
              )}
              {isStreaming && (
                <span className="ml-3 text-sm font-sans text-accent">
                  流式输出中…
                </span>
              )}
            </h2>
            {generated && !isStreaming && (
              <button
                type="button"
                onClick={handleCopy}
                className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
              >
                {copied ? "已复制 ✓" : "复制到剪贴板"}
              </button>
            )}
          </div>
          <div className="rule-thin mb-6" />

          {isStreaming || !generated ? (
            <div className="p-6 border border-rule rounded-card bg-subtle whitespace-pre-wrap text-sm text-ink min-h-24">
              {streamingText}
              {isStreaming && (
                <span className="inline-block w-2 h-4 ml-0.5 bg-accent animate-pulse align-middle" />
              )}
            </div>
          ) : (
            <div className="p-6 border border-rule rounded-card bg-subtle">
              <h3 className="text-lg font-serif text-ink mb-3">
                {generated.question}
              </h3>
              <ul className="space-y-1 mb-4">
                {generated.options.map((opt) => (
                  <li
                    key={opt}
                    className={`text-sm ${
                      opt.startsWith(generated.answer + ".")
                        ? "text-accent font-serif"
                        : "text-ink-muted"
                    }`}
                  >
                    {opt}
                  </li>
                ))}
              </ul>
              <p className="text-sm text-ink mb-2">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  答案
                </span>{" "}
                <span className="font-serif text-accent">{generated.answer}</span>
              </p>
              <p className="text-sm text-ink-muted whitespace-pre-wrap">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  解析
                </span>
                {"\n"}
                {generated.explanation}
              </p>
            </div>
          )}
        </section>
      )}

      {/* 生成历史 */}
      {history.length > 0 && (
        <section>
          <div className="flex items-baseline justify-between mb-4">
            <h2 className="text-xl font-serif text-ink">
              生成历史
              <span className="ml-2 text-sm font-sans text-ink-muted">
                {history.length} 条
              </span>
            </h2>
          </div>
          <div className="rule-thin mb-6" />
          <ul className="space-y-0">
            {history.map((h) => (
              <li
                key={h.id}
                className="py-3 grid grid-cols-12 gap-4 items-baseline border-b border-rule"
              >
                <div className="col-span-9">
                  <h3 className="text-sm font-serif text-ink">{h.question}</h3>
                  <p className="mt-1 text-tiny text-ink-muted">
                    答案：{h.answer}
                  </p>
                </div>
                <div className="col-span-3 text-right text-tiny font-mono text-ink-subtle">
                  {h.id}
                </div>
              </li>
            ))}
          </ul>
        </section>
      )}
    </div>
  );
}
