import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api, type TradeAccount } from "../../lib/api";

const PRESETS_GOOD = [
  { id: "keep", label: "績效不錯 · 維持策略", text: "績效表現良好，核准現有策略與節奏，繼續照此執行，不需大幅調整。" },
  { id: "scale", label: "績效不錯 · 適度加碼", text: "績效表現良好，在風控範圍內可適度提高倉位與進場積極度（單檔仍不超過總資產 40%）。" },
  { id: "star", label: "設為主力 AI", text: "績效表現良好，列為主力模擬帳號：維持策略、優先執行、盤中可略積極但仍守紀律。" },
];

const PRESETS_OTHER = [
  { id: "hold", label: "暫停新進場", text: "暫停新買進，僅管理現有持倉，觀望為主。" },
  { id: "tight", label: "收緊風控", text: "降低曝險，減少新倉，優先減碼虧損部位。" },
  { id: "clear", label: "清除指令", text: "" },
];

function fmtPct(v: number | null | undefined) {
  if (v == null || Number.isNaN(v)) return null;
  return `${v > 0 ? "+" : ""}${v.toFixed(1)}%`;
}

export function TraderDirectivePanel({
  account,
  returnPct,
  totalPnl,
}: {
  account: TradeAccount;
  returnPct?: number | null;
  totalPnl?: number | null;
}) {
  const qc = useQueryClient();
  const [draft, setDraft] = useState(account.userDirective || "");
  const performingWell = returnPct != null && returnPct > 0;

  const saveMut = useMutation({
    mutationFn: (directive: string) => api.setTraderDirective(account.id, directive),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["trade-accounts"] });
      qc.invalidateQueries({ queryKey: ["trader-brief", account.id] });
      qc.invalidateQueries({ queryKey: ["trade-dashboard", account.id] });
    },
  });

  const apply = (text: string) => {
    setDraft(text);
    saveMut.mutate(text);
  };

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

  return (
    <div className="journal-trader-block journal-directive-panel">
      <div className="journal-directive-head">
        <strong className="small">老闆指令</strong>
        {returnPct != null ? (
          <span className="small muted">
            總報酬 {fmtPct(returnPct)}
            {totalPnl != null ? ` · 損益 $${Math.round(totalPnl).toLocaleString()}` : ""}
          </span>
        ) : null}
      </div>
      <p className="small muted">
        觀察績效後下達正式指令，開盤前／盤中／盤後 AI 都會遵守（與貓頭鷹對話分開）。
      </p>
      {account.userDirective && !saveMut.isPending ? (
        <div className="journal-directive-current">
          <span className="small muted">目前生效：</span>
          <p className="small">{account.userDirective}</p>
        </div>
      ) : null}
      {performingWell ? (
        <div className="journal-directive-presets">
          <span className="small muted">績效為正，快捷指令：</span>
          <div className="journal-directive-btns">
            {PRESETS_GOOD.map((p) => (
              <button key={p.id} type="button" className="btn-ghost sm" disabled={saveMut.isPending} onClick={() => apply(p.text)}>
                {p.label}
              </button>
            ))}
          </div>
        </div>
      ) : null}
      <div className="journal-directive-presets">
        <span className="small muted">其他：</span>
        <div className="journal-directive-btns">
          {PRESETS_OTHER.map((p) => (
            <button key={p.id} type="button" className="btn-ghost sm" disabled={saveMut.isPending} onClick={() => apply(p.text)}>
              {p.label}
            </button>
          ))}
        </div>
      </div>
      <textarea
        className="skill-notes-textarea mt-s"
        rows={3}
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        placeholder="自訂指令，例：績效不錯，維持現策略；或：暫停買進兩天觀察…"
      />
      <div className="journal-toolbar mt-s">
        <button
          type="button"
          className="btn-primary sm"
          disabled={saveMut.isPending}
          onClick={() => saveMut.mutate(draft.trim())}
        >
          {saveMut.isPending ? "下達中…" : "下達指令"}
        </button>
      </div>
      {saveMut.error ? (
        <p className="small" style={{ color: "var(--crimson)", marginTop: 8 }}>
          {(saveMut.error as Error).message}
        </p>
      ) : null}
    </div>
  );
}