import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api, type SimulationRun, type TradeAccount } from "../../lib/api";
import MarkdownMessage from "../MarkdownMessage";
import { Card } from "../ui";
import { AppIcon } from "../PixelIcons";
import { TraderChatPanel } from "./TraderChatPanel";
import { TraderDirectivePanel } from "./TraderDirectivePanel";
import { TraderAnalysisReport, TraderIntradayReviews } from "./TraderAnalysisReport";
import { TraderFollowPanel } from "./TraderFollowPanel";
import { TraderStatusPanel } from "./TraderStatusPanel";

const PERSONALITY_LABELS: Record<string, string> = {
  buffett: "巴菲特 · 保守",
  dalio: "達里歐 · 穩健",
  lynch: "林區 · 均衡",
  ptj: "都鐸瓊斯 · 紀律",
  druckenmiller: "德魯肯米勒 · 進攻",
  soros: "索羅斯 · 激進",
  livermore: "利佛摩 · 投機",
  custom: "自訂",
};

function personalityLabel(id: string) {
  return PERSONALITY_LABELS[id] || id;
}

function fmtTime(ts: number | null | undefined) {
  if (!ts) return "尚未執行";
  return new Date(ts).toLocaleString("zh-TW", { hour: "2-digit", minute: "2-digit", month: "short", day: "numeric" });
}

const UNIVERSE_LABEL: Record<string, string> = {
  watchlist: "追蹤清單",
  ai_pick: "AI 自選",
};

function universeLabel(raw?: string | null) {
  const u = String(raw || "watchlist").trim().toLowerCase();
  if (UNIVERSE_LABEL[u]) return UNIVERSE_LABEL[u];
  if (u === "ai" || u === "auto") return "AI 自選";
  return `自訂：${raw}`;
}

const PHASE_LABEL: Record<string, string> = {
  pre_market: "市場分析",
  intraday: "盤中",
  intraday_review: "盤中復盤",
  post_market: "盤後",
  industry_report: "每日產業研究",
};

function statusTone(status: string): "up" | "down" | "cool" {
  if (status === "ok") return "up";
  if (status === "error" || status === "parse_error") return "down";
  return "cool";
}

function fmtMoney(v: number | null | undefined) {
  if (v == null || Number.isNaN(v)) return "—";
  return `$${v.toLocaleString(undefined, { maximumFractionDigits: 0 })}`;
}

function RunRow({ run }: { run: SimulationRun }) {
  const buyRows = run.executed.filter((e) => e.type === "buy" && e.ok);
  const sellRows = run.executed.filter((e) => e.type === "sell" && e.ok);
  const phase = run.phase ? PHASE_LABEL[run.phase] || run.phase : "";
  return (
    <div className="journal-sim-run">
      <div className="journal-sim-run-head">
        <span className="small muted">
          {phase ? `[${phase}] ` : ""}
          {run.createdAtIso ? new Date(run.createdAtIso).toLocaleString("zh-TW") : "—"}
        </span>
        <span className={`journal-sim-status ${statusTone(run.status)}`}>{run.status}</span>
      </div>
      {run.summary ? <p className="small">{run.summary}</p> : null}
      {run.phase === "intraday" ? (
        <div className="small muted">
          {buyRows.length > 0 ? (
            <div className="trader-entry-sizing">
              {buyRows.map((b) => (
                <div key={`${b.tradeId ?? b.symbol}-${b.shares}`} className="trader-entry-sizing-row">
                  <strong>
                    {b.symbol || "—"} 進場 {b.shares != null ? `${b.shares} 張` : "— 張"}
                    {b.price != null ? ` @ ${fmtMoney(b.price)}` : ""}
                    {b.cost != null ? ` = ${fmtMoney(b.cost)}` : ""}
                    {b.assetPct != null ? ` · 佔資產 ${b.assetPct.toFixed(1)}%` : ""}
                  </strong>
                </div>
              ))}
            </div>
          ) : null}
          {run.executed.filter((e) => !e.ok && e.error === "market_closed").length > 0 ? (
            <p style={{ color: "var(--gold)", marginTop: 4 }}>非交易時段，買賣已拒絕</p>
          ) : null}
          {run.executed.filter((e) => !e.ok && e.error === "weak_reason").map((e) => (
            <p key={`weak-${e.symbol}`} style={{ color: "var(--crimson)", marginTop: 4 }}>
              {e.symbol || "買進"} 理由不足未成交{e.note ? `：${e.note}` : ""}
            </p>
          ))}
          {sellRows.length > 0 ? (
            <p style={{ marginTop: buyRows.length ? 4 : 0 }}>
              賣出 {sellRows.map((s) => s.symbol).filter(Boolean).join("、") || sellRows.length}
            </p>
          ) : null}
          {!buyRows.length && !sellRows.length ? <p>本輪無成交</p> : null}
        </div>
      ) : null}
      {run.error ? <p className="small muted">{run.error}</p> : null}
    </div>
  );
}

export function SimulationPanel({
  account,
  onRunPhase,
  running,
  returnPct,
  totalPnl,
}: {
  account: TradeAccount;
  onRunPhase: (phase: string) => void;
  running?: boolean;
  returnPct?: number | null;
  totalPnl?: number | null;
}) {
  const queryClient = useQueryClient();
  const runsQ = useQuery({
    queryKey: ["simulation-runs", account.id],
    queryFn: () => api.simulationRuns(account.id),
    enabled: account.kind === "ai",
    refetchInterval: account.simulationEnabled ? 60_000 : false,
  });
  const briefQ = useQuery({
    queryKey: ["trader-brief", account.id],
    queryFn: () => api.traderBrief(account.id),
    enabled: account.kind === "ai",
    refetchInterval: account.simulationEnabled ? 120_000 : false,
  });
  const takeawayM = useMutation({
    mutationFn: () => api.refreshDailyTakeaway(account.id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["trader-brief", account.id] }),
  });

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

  const runs = runsQ.data?.runs || [];
  const brief = briefQ.data;
  const preReport = brief?.brief?.preReport;
  const industryReport = brief?.brief?.industryReport;
  const industryReports = brief?.brief?.industryReports || [];
  const intradayReviews = brief?.brief?.intradayReviews || [];
  const lessons = brief?.brief?.lessons || [];
  const strategy = brief?.brief?.strategy;
  const todayTakeaway = brief?.brief?.todayTakeaway;
  const dailyTakeaways = brief?.brief?.dailyTakeaways || [];
  const canTrade = brief?.canTrade ?? false;
  const marketStatus = brief?.marketStatus || runsQ.data?.marketStatus || "—";
  const phaseLabel = brief?.phaseLabel || "—";
  const operational = brief?.operationalStatus;
  const effectiveParams = brief?.effectiveParams;
  const todaySignals = brief?.followSignals?.signals?.length || 0;
  const intradayRuns = operational?.today.intradayRuns || 0;
  const tradingDay = operational?.tradingDay !== false;

  return (
    <>
      <Card title="AI 交易員控制台" ico={<AppIcon name="wizard" size={22} framed variant="nav" />} className="mt ai-command-card">
        <div className="ai-command-grid">
          <div className="ai-command-stat">
            <span className="k">市場階段</span>
            <strong>{phaseLabel}</strong>
            <span className="s">{marketStatus}</span>
          </div>
          <div className="ai-command-stat">
            <span className="k">運作狀態</span>
            <strong className={`tone-${statusTone(operational?.health === "ready" ? "ok" : operational?.health || "")}`}>
              {operational?.healthLabel || "讀取中"}
            </strong>
            <span className="s">{account.simulationEnabled ? "自動排程開啟" : "僅手動執行"}</span>
          </div>
          <div className="ai-command-stat">
            <span className="k">今日盤中</span>
            <strong>{intradayRuns} 輪</strong>
            <span className="s">{operational?.today.preReport ? "市場分析已完成" : "尚未完成市場分析"}</span>
          </div>
          <div className="ai-command-stat">
            <span className="k">每日產業報告</span>
            <strong>{industryReport ? "已產出" : "尚未"}</strong>
            <span className="s">{todaySignals} 筆今日訊號</span>
          </div>
        </div>

        <div className="ai-command-meta">
          <span>{personalityLabel(account.traderPersonality || "custom")}</span>
          <span>{account.aiProvider || "預設 Provider"} {account.aiModel ? `/ ${account.aiModel}` : ""}</span>
          <span>盤中每 {account.simulationIntervalMin || 30} 分鐘</span>
          <span>{universeLabel(account.simulationUniverse)}</span>
        </div>

        {effectiveParams ? (
          <section className="trader-effective-params">
            <div className="trader-effective-head">
              <div>
                <span>目前真正生效</span>
                <strong>{effectiveParams.personalityName} · 交易參數</strong>
              </div>
              <span className="trader-effective-badge">{effectiveParams.custom ? "自訂參數" : "模板＋帳號設定"}</span>
            </div>
            <div className="trader-effective-grid">
              {effectiveParams.core.map((param) => (
                <div key={param.key} className="trader-effective-stat">
                  <span>{param.label}</span>
                  <strong>{param.value}{param.unit || ""}</strong>
                  <small>{param.source}</small>
                </div>
              ))}
            </div>
            {(effectiveParams.templateParams.length > 0 || effectiveParams.strategyNumberClauses.length > 0) ? (
              <details className="trader-effective-more">
                <summary>
                  查看所有數值條款（{effectiveParams.templateParams.length + effectiveParams.strategyNumberClauses.length}）
                </summary>
                {effectiveParams.templateParams.length > 0 ? (
                  <div className="trader-effective-table">
                    {effectiveParams.templateParams.map((param) => (
                      <div key={param.key}>
                        <span>{param.label}</span>
                        <strong>{param.value || "策略定義"}</strong>
                        <small>{param.description} · {param.source}</small>
                      </div>
                    ))}
                  </div>
                ) : null}
                {effectiveParams.strategyNumberClauses.length > 0 ? (
                  <div className="trader-effective-clauses">
                    <span>策略全文中的數字條款</span>
                    <ul>
                      {effectiveParams.strategyNumberClauses.map((clause) => <li key={clause}>{clause}</li>)}
                    </ul>
                  </div>
                ) : null}
              </details>
            ) : null}
          </section>
        ) : null}

        <div className="ai-command-actions">
          <div>
            <strong>今日操作</strong>
            <span>{canTrade ? "交易時段中，可執行盤中一輪" : `目前 ${marketStatus}，盤中買賣暫停`}</span>
          </div>
          <div className="journal-toolbar">
            <button type="button" className="btn-primary sm" disabled={running || !tradingDay} onClick={() => onRunPhase("pre_market")}>
              ① 盤前研究
            </button>
            <button
              type="button"
              className="btn-ghost sm"
              disabled={running || !canTrade}
              title={canTrade ? "盤中交易（僅交易時段）" : "非交易時段不可買賣"}
              onClick={() => onRunPhase("intraday")}
            >
              ② 盤中一輪
            </button>
            <button type="button" className="btn-ghost sm" disabled={running || !tradingDay} onClick={() => onRunPhase("post_market")}>
              ③ 盤後復盤
            </button>
            <button type="button" className="btn-ghost sm" disabled={running || !!industryReport} onClick={() => onRunPhase("industry_report")}>
              每日產業研究
            </button>
          </div>
        </div>

        {strategy ? (
          <div className="ai-command-strategy">
            <span>今日策略</span>
            <p>{strategy}</p>
          </div>
        ) : (
          <p className="ai-command-empty small">尚未有今日策略，先執行「① 市場分析」。</p>
        )}

        <section className="daily-takeaway">
          <div className="daily-takeaway-head">
            <div>
              <span>每日學習日誌</span>
              <strong>今日 Takeaway</strong>
            </div>
            <button
              type="button"
              className="btn-ghost sm"
              disabled={takeawayM.isPending}
              onClick={() => takeawayM.mutate()}
            >
              {takeawayM.isPending ? "整理中…" : "重新整理"}
            </button>
          </div>
          {todayTakeaway ? (
            <>
              <MarkdownMessage text={todayTakeaway.body} />
              <p className="daily-takeaway-updated small muted">
                最後整理：{fmtTime(todayTakeaway.createdAtIso ? new Date(todayTakeaway.createdAtIso).getTime() : null)}
              </p>
            </>
          ) : (
            <p className="small muted">執行一次市場分析或按「重新整理」，今天就會留下可回看的 Takeaway。</p>
          )}
        </section>

        <TraderFollowPanel payload={brief?.followSignals} />

        {!tradingDay ? (
          <p className="small ai-command-notice">今日休市：盤前、盤中與盤後分析全部停用；每日產業研究仍會自動產出並保存歷史。</p>
        ) : !canTrade ? (
          <p className="small ai-command-notice">目前非盤中；盤中買賣暫停。</p>
        ) : null}

        <div className="ai-command-details">
          <details open>
            <summary>今日每日產業研究報告</summary>
            {industryReport ? (
              <>
                <div className="ai-command-meta">
                  <span>專業產業專題</span>
                  <span>分析師共識 {(industryReport.meta as any)?.researchSources?.analystSymbols?.length || 0} 檔</span>
                  <span>國會公開披露 {(industryReport.meta as any)?.researchSources?.congressDisclosureCount || 0} 筆</span>
                  <span>政策訊號 {(industryReport.meta as any)?.researchSources?.policyPostCount || 0} 則</span>
                </div>
                {(industryReport.meta as any)?.industryFocus ? (
                  <div className="ai-command-strategy">
                    <span>今日選題 · {(industryReport.meta as any).industryFocus.industry || "產業焦點"}</span>
                    <p>{(industryReport.meta as any).industryFocus.why_today}</p>
                  </div>
                ) : null}
                <div className="editorial small trader-report-markdown">
                  <MarkdownMessage text={industryReport.body} />
                </div>
                <p className="small muted">國會議員交易為公開延遲披露，只作研究線索；不代表政策因果、內線資訊或買賣建議。</p>
              </>
            ) : (
              <p className="small muted">
                將於美東開盤前 30 分鐘固定產出：聚焦一個細產業，整合供需與供應鏈、分析師共識、國會公開披露及政策影響。
              </p>
            )}
          </details>
          <details open>
            <summary>今日市場分析與完整報告</summary>
            {preReport ? <TraderAnalysisReport preReport={preReport} /> : <p className="small muted">尚未產生市場分析。</p>}
          </details>
          <details>
            <summary>AI 運作狀態與排程</summary>
            <TraderStatusPanel status={operational} />
          </details>
          <details>
            <summary>正式指令與交易限制</summary>
            <TraderDirectivePanel account={account} returnPct={returnPct} totalPnl={totalPnl} />
          </details>
          <details>
            <summary>盤中復盤與累積教訓</summary>
            <TraderIntradayReviews reviews={intradayReviews} />
            {lessons.length > 0 ? (
              <div className="journal-trader-block mt-s">
                <div className="small muted">累積教訓（獨立記憶）</div>
                <div className="dl">
                  {lessons.slice(0, 5).map((l) => (
                    <div className="row" key={l.id}>
                      <span className="k">{l.title || l.day}</span>
                      <span className="v small">{l.body.slice(0, 120)}{l.body.length > 120 ? "…" : ""}</span>
                    </div>
                  ))}
                </div>
              </div>
            ) : <p className="small muted">尚無盤中復盤或累積教訓。</p>}
          </details>
          <details>
            <summary>每日產業研究歷史（{industryReports.length}）</summary>
            {industryReports.length > 0 ? (
              <div className="daily-takeaway-history">
                {industryReports.map((item) => (
                  <details key={item.id} open={item.day === brief?.brief?.day}>
                    <summary>{item.day || item.title || "每日產業研究"}</summary>
                    <MarkdownMessage text={item.body} />
                  </details>
                ))}
              </div>
            ) : <p className="small muted">尚無每日產業研究報告。</p>}
          </details>
          <details>
            <summary>每日 Takeaway 歷史（{dailyTakeaways.length}）</summary>
            {dailyTakeaways.length > 0 ? (
              <div className="daily-takeaway-history">
                {dailyTakeaways.map((item) => (
                  <details key={item.id} open={item.day === brief?.brief?.day}>
                    <summary>{item.day || item.title || "每日 Takeaway"}</summary>
                    <MarkdownMessage text={item.body} />
                  </details>
                ))}
              </div>
            ) : <p className="small muted">尚無每日 Takeaway。</p>}
          </details>
          <details>
            <summary>最近執行紀錄（{runs.length}）</summary>
            {runs.length > 0 ? (
              <div className="journal-sim-runs">
                {runs.slice(0, 10).map((r) => <RunRow key={r.id} run={r} />)}
              </div>
            ) : <p className="muted small">尚無執行紀錄。</p>}
          </details>
        </div>
      </Card>

      <TraderChatPanel account={account} />
    </>
  );
}
