import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api, type TradeAccount } from "../../lib/api";
import { aiApi } from "../../lib/ai";
import { AppIcon } from "../PixelIcons";
import MarkdownMessage from "../MarkdownMessage";

type Msg = { id: string; role: string; text: string; meta?: string };

const QUICK_PROMPTS = [
  "用一句話告訴我今天最重要的判斷",
  "解釋今天為什麼沒有交易",
  "明天開盤前我最該注意什麼？",
];

export function TraderChatPanel({ account }: { account: TradeAccount }) {
  const qc = useQueryClient();
  const chatQ = useQuery({
    queryKey: ["trader-chat", account.id],
    queryFn: () => api.traderChat(account.id),
    enabled: account.kind === "ai",
  });
  const briefQ = useQuery({
    queryKey: ["trader-brief", account.id],
    queryFn: () => api.traderBrief(account.id),
    enabled: account.kind === "ai",
  });

  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Msg[]>([]);
  const [open, setOpen] = useState(false);
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chatQ.data?.messages) setMessages(chatQ.data.messages);
  }, [chatQ.data]);

  useEffect(() => {
    if (open) endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, open]);

  useEffect(() => {
    if (!open) return undefined;
    document.body.classList.add("skill-modal-open");
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKeyDown);
    return () => {
      document.body.classList.remove("skill-modal-open");
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  useEffect(() => {
    setOpen(false);
  }, [account.id]);

  const saveMut = useMutation({
    mutationFn: (msgs: Msg[]) => api.saveTraderChat(account.id, msgs),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["trader-chat", account.id] }),
  });

  const sendMut = useMutation({
    mutationFn: async (question: string) => {
      const status = await aiApi.status();
      if (!status.ready) throw new Error("請先在設定頁完成 AI 設定");
      const provider = (account.aiProvider as "grok" | "opencode-go") || status.active;
      const userMsg: Msg = { id: `u_${Date.now()}`, role: "user", text: question };
      const next = [...messages, userMsg];
      setMessages(next);
      const brief = briefQ.data;
      const ctx = await aiApi.context("journal", { view: "journal", cardTitle: "AI交易員" }, {
        accountId: account.id,
        traderMode: true,
        traderBrief: brief?.brief,
      });
      const res = await aiApi.chat({
        provider,
        model: account.aiModel || undefined,
        question: `[AI交易員獨立對話·非貓頭鷹] ${question}`,
        context: ctx,
      });
      const assistant: Msg = {
        id: `a_${Date.now()}`,
        role: "assistant",
        text: res.text,
        meta: `${provider}${account.aiModel ? ` · ${account.aiModel}` : ""}`,
      };
      const finalMsgs = [...next, assistant];
      setMessages(finalMsgs);
      await saveMut.mutateAsync(finalMsgs);
      return res.text;
    },
  });

  if (account.kind !== "ai") return null;

  const submit = (text = input) => {
    const question = text.trim();
    if (!question || sendMut.isPending) return;
    sendMut.mutate(question);
    setInput("");
  };
  const lastMessage = messages[messages.length - 1];

  return (
    <>
      <button type="button" className="trader-summon mt" onClick={() => setOpen(true)}>
        <span className="trader-summon-orb" aria-hidden>
          <AppIcon name="wizard" size={26} variant="nav" />
        </span>
        <span className="trader-summon-copy">
          <span className="trader-summon-kicker">ARCANE MARKET LINK</span>
          <strong>召喚 {account.name} 交易員</strong>
          <span>{lastMessage ? lastMessage.text.slice(0, 76) : "詢問策略、進出場理由與今日教訓"}</span>
        </span>
        <span className="trader-summon-status">
          <i />
          {messages.length ? `${messages.length} 則記憶` : "通訊待命"}
        </span>
      </button>

      {open ? (
        <div className="trader-chat-modal" role="dialog" aria-modal="true" aria-label={`${account.name} AI 交易員對話`}>
          <button type="button" className="trader-chat-backdrop" aria-label="關閉交易員對話" onClick={() => setOpen(false)} />
          <section className="trader-chat-console">
            <div className="trader-chat-runes" aria-hidden>✦ · · ✧ · · ✦</div>
            <header className="trader-chat-head">
              <span className="trader-chat-avatar" aria-hidden>
                <AppIcon name="wizard" size={30} variant="nav" />
              </span>
              <div>
                <span className="trader-chat-kicker">奧術市場通訊</span>
                <strong>{account.name} · AI 交易員</strong>
                <small>
                  {account.aiProvider || "預設 Provider"}
                  {account.aiModel ? ` / ${account.aiModel}` : ""} · 獨立記憶已連線
                </small>
              </div>
              <button type="button" className="trader-chat-close" aria-label="關閉" onClick={() => setOpen(false)}>×</button>
            </header>

            <div className="trader-chat-log">
              {messages.length === 0 ? (
                <div className="trader-chat-empty">
                  <span className="trader-chat-empty-glyph">✧</span>
                  <strong>通訊法陣已啟動</strong>
                  <p>交易員能讀取自己的策略、執行紀錄、每日 Takeaway 與累積教訓。</p>
                </div>
              ) : (
                messages.map((m) => (
                  <div key={m.id} className={`trader-chat-msg ${m.role}`}>
                    <div className="trader-chat-role">{m.role === "user" ? "冒險者" : account.name}</div>
                    <div className="trader-chat-text">
                      <MarkdownMessage text={m.text} />
                    </div>
                    {m.meta ? <div className="trader-chat-meta">{m.meta}</div> : null}
                  </div>
                ))
              )}
              {sendMut.isPending ? (
                <div className="trader-chat-casting">
                  <span /><span /><span /> 正在解讀市場記憶
                </div>
              ) : null}
              <div ref={endRef} />
            </div>

            <footer className="trader-chat-compose">
              <div className="trader-chat-prompts">
                {QUICK_PROMPTS.map((prompt) => (
                  <button key={prompt} type="button" disabled={sendMut.isPending} onClick={() => submit(prompt)}>
                    {prompt}
                  </button>
                ))}
              </div>
              <div className="trader-chat-input">
                <textarea
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder="向交易員詢問……"
                  rows={2}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && !e.shiftKey) {
                      e.preventDefault();
                      submit();
                    }
                  }}
                />
                <button type="button" disabled={sendMut.isPending || !input.trim()} onClick={() => submit()}>
                  <span>施放</span>
                  <small>ENTER</small>
                </button>
              </div>
              {sendMut.error ? <p className="trader-chat-error">{(sendMut.error as Error).message}</p> : null}
            </footer>
          </section>
        </div>
      ) : null}
    </>
  );
}
