"use client";

/**
 * AI 辅学页面（ai14，P5 可选）
 *
 * - 聊天界面，SSE 流式回答
 * - 消息列表（用户 + AI）
 * - 输入框 + 发送按钮
 * - Mock 模式（NEXT_PUBLIC_API_MOCKING=enabled）：本地模拟流式回答
 * - 未启用时通过 FeatureFlag 展示"AI 辅学功能开发中"占位
 */

import { useCallback, useEffect, useRef, useState } from "react";
import { FeatureFlag } from "@/components/feature-flag";

interface ChatMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
}

const MOCK_REPLY =
  "这是一个很好的问题。根据你提到的知识点，建议你先回顾相关定义，再通过例题巩固。我可以帮你梳理思路：首先明确题干要求，其次列出已知条件，最后逐步推导结论。";

function useAiTutorEnabled(): boolean {
  return (
    process.env.NEXT_PUBLIC_FEATURE_AI_TUTOR === "true" ||
    process.env.NEXT_PUBLIC_API_MOCKING === "enabled"
  );
}

function isMockMode(): boolean {
  return process.env.NEXT_PUBLIC_API_MOCKING === "enabled";
}

/** 流式追加文本到指定消息 */
function streamInto(
  messages: ChatMessage[],
  id: string,
  append: (full: string) => void,
): (chunk: string) => void {
  let acc = messages.find((m) => m.id === id)?.content ?? "";
  return (chunk: string) => {
    acc += chunk;
    append(acc);
  };
}

function ChatInterface(): React.ReactNode {
  const mocking = isMockMode();
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: "welcome",
      role: "assistant",
      content: "你好！我是 AI 学习助手，有什么可以帮你的吗？",
    },
  ]);
  const [input, setInput] = useState("");
  const [streaming, setStreaming] = useState(false);
  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    listRef.current?.scrollTo({
      top: listRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [messages]);

  const send = useCallback(async (): Promise<void> => {
    const text = input.trim();
    if (!text || streaming) return;

    const userMsg: ChatMessage = {
      id: `u-${Date.now()}`,
      role: "user",
      content: text,
    };
    const aiId = `a-${Date.now()}`;
    const aiMsg: ChatMessage = { id: aiId, role: "assistant", content: "" };
    setMessages((prev) => [...prev, userMsg, aiMsg]);
    setInput("");
    setStreaming(true);

    const updateAi = (full: string): void => {
      setMessages((prev) =>
        prev.map((m) => (m.id === aiId ? { ...m, content: full } : m)),
      );
    };
    const sink = streamInto(messages, aiId, updateAi);

    try {
      if (mocking) {
        // Mock：按字符流式输出
        const chars = Array.from(MOCK_REPLY);
        for (let i = 0; i < chars.length; i += 1) {
          await new Promise((resolve) => window.setTimeout(resolve, 20));
          sink(chars[i] ?? "");
        }
      } else {
        // 真实 SSE：POST 请求并以 reader 解析 data: 行
        const res = await fetch("/api/v1/student/ai-tutor", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ message: text }),
        });
        if (!res.ok || !res.body) throw new Error("请求失败");
        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        for (;;) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split("\n");
          buffer = lines.pop() ?? "";
          for (const line of lines) {
            const trimmed = line.trim();
            if (trimmed.startsWith("data:")) {
              const payload = trimmed.slice(5).trim();
              if (payload === "[DONE]") break;
              sink(payload);
            }
          }
        }
      }
    } catch {
      updateAi("回答生成失败，请重试");
    } finally {
      setStreaming(false);
    }
  }, [input, streaming, mocking, messages]);

  const handleClear = useCallback((): void => {
    setMessages([
      {
        id: "welcome",
        role: "assistant",
        content: "你好！我是 AI 学习助手，有什么可以帮你的吗？",
      },
    ]);
  }, []);

  return (
    <main
      className="px-md py-lg max-w-3xl mx-auto flex flex-col"
      style={{ minHeight: "70vh" }}
    >
      <header className="mb-md">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="font-serif text-2xl text-ink">AI 辅学</h1>
            <p className="mt-xs text-sm text-ink-muted">智能答疑与学习辅导</p>
          </div>
          <button type="button" className="btn-secondary" onClick={handleClear}>
            清空对话
          </button>
        </div>
      </header>

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

      <div
        ref={listRef}
        className="flex-1 overflow-y-auto space-y-md py-md"
        role="log"
        aria-live="polite"
        aria-label="对话记录"
      >
        {messages.map((m) => (
          <article
            key={m.id}
            className={`flex ${m.role === "user" ? "justify-end" : "justify-start"}`}
          >
            <div
              className={`card-paper px-md py-sm max-w-[85%] ${
                m.role === "user" ? "bg-accent-muted" : ""
              }`}
            >
              <p className="text-xs text-ink-subtle mb-xs">
                {m.role === "user" ? "我" : "AI 助手"}
              </p>
              <p className="text-sm text-ink whitespace-pre-wrap break-words">
                {m.content || (streaming ? "正在思考…" : "")}
              </p>
            </div>
          </article>
        ))}
      </div>

      <form
        className="flex gap-sm pt-md"
        onSubmit={(e) => {
          e.preventDefault();
          void send();
        }}
      >
        <label htmlFor="ai-input" className="sr-only">
          请输入你的问题
        </label>
        <input
          id="ai-input"
          className="input-paper flex-1"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="请输入你的问题…"
          disabled={streaming}
          aria-label="问题输入框"
        />
        <button
          type="submit"
          className="btn-primary"
          disabled={streaming || !input.trim()}
        >
          {streaming ? "正在思考…" : "发送"}
        </button>
      </form>
    </main>
  );
}

export default function AiTutorPage(): React.ReactNode {
  const enabled = useAiTutorEnabled();
  return (
    <FeatureFlag enabled={enabled}>
      <ChatInterface />
    </FeatureFlag>
  );
}
