import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { api, type TradeAccount, type TraderCustomConfig } from "../../lib/api";
import { aiApi, type AIProviderId } from "../../lib/ai";
import { AppIcon } from "../PixelIcons";
import { TraderPersonalityPicker } from "./TraderPersonalityPicker";

export type UniverseMode = "watchlist" | "ai_pick" | "custom";

export type AccountForm = {
  name: string;
  kind: "human" | "ai";
  cash: string;
  initialCapital: string;
  aiEnabled: boolean;
  simulationEnabled: boolean;
  simulationIntervalMin: string;
  simulationMarket: string;
  universeMode: UniverseMode;
  universeCustom: string;
  simulationOnlyMarketHours: boolean;
  aiProvider: string;
  aiModel: string;
  traderPersonality: string;
  traderConfig: TraderCustomConfig;
  simulationStrategy: string;
  note: string;
};

export const DEFAULT_TRADER_CONFIG: TraderCustomConfig = {
  riskScore: 5,
  maxPositionPct: 30,
  maxActionsPerRound: 2,
  maxOpenPositions: 8,
  minCashReservePct: 10,
  observation: {
    preMarket: ["總經、利率、美元與 VIX", "板塊輪動與候選標的新聞"],
    intraday: ["持倉盈虧與停損停利", "大盤方向與量價關鍵位"],
    postMarket: ["是否遵守策略與風控", "今日教訓與明日行動"],
  },
  tradingRules: {
    entry: ["符合自訂策略且理由完整才進場"],
    exit: ["假設失效或觸及停損時出場"],
    sizing: ["遵守單檔與持倉檔數上限"],
    forbidden: ["禁止無理由交易與違反風控"],
  },
  paramOverrides: {},
};

function parseUniverse(raw?: string | null): { mode: UniverseMode; custom: string } {
  const u = String(raw || "watchlist").trim().toLowerCase();
  if (u === "watchlist") return { mode: "watchlist", custom: "" };
  if (u === "ai_pick" || u === "ai" || u === "auto") return { mode: "ai_pick", custom: "" };
  return { mode: "custom", custom: String(raw || "").trim() };
}

export function accountFormFromRecord(a: TradeAccount): AccountForm {
  const { mode, custom } = parseUniverse(a.simulationUniverse);
  const savedConfig = a.traderConfig || {};
  return {
    name: a.name,
    kind: a.kind === "ai" ? "ai" : "human",
    cash: String(a.cash ?? 0),
    initialCapital: a.initialCapital != null ? String(a.initialCapital) : "",
    aiEnabled: !!a.aiEnabled,
    simulationEnabled: !!a.simulationEnabled,
    simulationIntervalMin: String(a.simulationIntervalMin ?? 30),
    simulationMarket: a.simulationMarket || "ANY",
    universeMode: mode,
    universeCustom: custom,
    simulationOnlyMarketHours: a.simulationOnlyMarketHours !== false,
    aiProvider: a.aiProvider || "",
    aiModel: a.aiModel || "",
    traderPersonality: a.traderPersonality || "lynch",
    traderConfig: {
      ...DEFAULT_TRADER_CONFIG,
      ...savedConfig,
      observation: { ...DEFAULT_TRADER_CONFIG.observation, ...(savedConfig.observation || {}) },
      tradingRules: { ...DEFAULT_TRADER_CONFIG.tradingRules, ...(savedConfig.tradingRules || {}) },
      paramOverrides: { ...(savedConfig.paramOverrides || {}) },
    },
    simulationStrategy: a.simulationStrategy || "",
    note: a.note || "",
  };
}

export function accountSaveBlockReason(form: AccountForm, saving: boolean): string | null {
  if (saving) return null;
  if (!form.name.trim()) return "請先填寫帳號名稱";
  if (form.kind === "ai" && form.simulationEnabled && form.universeMode === "custom" && !form.universeCustom.trim()) {
    return "自訂標的範圍請至少填一個代號";
  }
  return null;
}

export function canSaveAccountForm(form: AccountForm, saving: boolean): boolean {
  if (saving) return false;
  return !accountSaveBlockReason(form, saving);
}

export const EMPTY_ACCOUNT_FORM: AccountForm = {
  name: "",
  kind: "human",
  cash: "0",
  initialCapital: "",
  aiEnabled: false,
  simulationEnabled: false,
  simulationIntervalMin: "30",
  simulationMarket: "US",
  universeMode: "watchlist",
  universeCustom: "",
  simulationOnlyMarketHours: true,
  aiProvider: "",
  aiModel: "",
  traderPersonality: "lynch",
  traderConfig: DEFAULT_TRADER_CONFIG,
  simulationStrategy: "",
  note: "",
};

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="journal-form-hint">{children}</p>;
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="journal-form-section">
      <div className="journal-form-section-title">{title}</div>
      {children}
    </div>
  );
}

export function AccountSettingsModal({
  open,
  editing,
  form,
  saving,
  onChange,
  onClose,
  onSave,
  onDelete,
  deleteError,
}: {
  open: boolean;
  editing: TradeAccount | null;
  form: AccountForm;
  saving: boolean;
  onChange: (patch: Partial<AccountForm>) => void;
  onClose: () => void;
  onSave: () => void;
  onDelete?: (opts: { force: boolean }) => void;
  deleteError?: string | null;
}) {
  const [deleteForce, setDeleteForce] = useState(false);

  useEffect(() => {
    document.body.classList.toggle("skill-modal-open", open);
    return () => document.body.classList.remove("skill-modal-open");
  }, [open]);

  useEffect(() => {
    if (!open) setDeleteForce(false);
  }, [open, editing?.id]);

  const purgeQ = useQuery({
    queryKey: ["trade-account-purge", editing?.id],
    queryFn: () => api.tradeAccountPurgeStats(editing!.id),
    enabled: open && !!editing?.id,
  });
  const purge = purgeQ.data;

  const providersQ = useQuery({
    queryKey: ["trade-ai-providers"],
    queryFn: api.tradeAiProviders,
    enabled: open && form.kind === "ai",
  });
  const providers = (providersQ.data?.providers || []).filter((p) => p.hasKey);
  const activeProviderId = (form.aiProvider || providers[0]?.id || "grok") as AIProviderId;

  const modelsQ = useQuery({
    queryKey: ["ai-models", activeProviderId],
    queryFn: () => aiApi.models(activeProviderId),
    enabled: open && form.kind === "ai" && providers.some((p) => p.id === activeProviderId),
    staleTime: 120_000,
  });
  const modelOptions = modelsQ.data?.models || [];
  const defaultModel = providers.find((p) => p.id === activeProviderId)?.model || modelOptions[0]?.id || "";

  const effectiveModel = form.aiModel || defaultModel;

  const templatesQ = useQuery({
    queryKey: ["trader-personality-templates"],
    queryFn: api.traderPersonalityTemplates,
    enabled: open && form.kind === "ai" && form.simulationEnabled,
  });

  useEffect(() => {
    if (!open || form.kind !== "ai" || !form.simulationEnabled || form.simulationStrategy.trim()) return;
    const templates = templatesQ.data?.templates;
    if (!templates?.length) return;
    const pid = form.traderPersonality || "lynch";
    const t = templates.find((x) => x.id === pid) || templates[0];
    if (t) onChange({ traderPersonality: t.id, simulationStrategy: t.strategy });
  }, [
    open,
    form.kind,
    form.simulationEnabled,
    form.simulationStrategy,
    form.traderPersonality,
    templatesQ.data,
    onChange,
  ]);

  const saveBlockReason = accountSaveBlockReason(form, saving);
  const canSave = canSaveAccountForm(form, saving);

  const universeBehavior = useMemo(() => {
    if (form.universeMode === "watchlist") {
      return "只在你 App 追蹤清單（watchlist）內找標的；盤中買賣不會超出清單。";
    }
    if (form.universeMode === "ai_pick") {
      return "盤前研究時 AI 依總經、輪動、新聞自選 5–8 檔寫入 watch_focus；盤中只在這個池子裡交易（可含清單外標的）。";
    }
    return "只交易你指定的代號（逗號分隔），例如 NVDA,AAPL,2330.TW。";
  }, [form.universeMode]);

  if (!open) return null;

  return (
    <div className="skill-modal" role="dialog" aria-modal="true">
      <button type="button" className="skill-modal-backdrop" aria-label="關閉" onClick={onClose} />
      <div className="skill-modal-panel journal-account-modal">
        <div className="skill-modal-head">
          <AppIcon name="coin" size={26} framed variant="hero" />
          <strong>{editing ? "帳號設定" : "新增帳號"}</strong>
          <button type="button" className="guide-close" onClick={onClose} aria-label="關閉">
            ×
          </button>
        </div>
        <div className="journal-form-body journal-form-scroll">
          <Section title="基本資料">
            <div className="settings-field">
              <label>帳號名稱 *</label>
              <input value={form.name} onChange={(e) => onChange({ name: e.target.value })} placeholder="我自己 / 巴菲特風格 AI" />
            </div>
            <div className="grid g2">
              <div className="settings-field">
                <label>類型</label>
                <select value={form.kind} onChange={(e) => onChange({ kind: e.target.value as "human" | "ai" })}>
                  <option value="human">自己操作</option>
                  <option value="ai">AI 自動投資（比績效、可跟單）</option>
                </select>
                <Hint>{form.kind === "ai" ? "AI 帳號會獨立跑盤前／盤中／盤後，與貓頭鷹分開。" : "手動記錄交易與復盤。"}</Hint>
              </div>
              <div className="settings-field">
                <label>現金餘額</label>
                <input
                  inputMode="decimal"
                  value={form.cash}
                  onChange={(e) => onChange({ cash: e.target.value })}
                  placeholder="用於計算股票/現金比例"
                />
              </div>
            </div>
            <div className="settings-field">
              <label>初始本金（選填）</label>
              <input
                inputMode="decimal"
                value={form.initialCapital}
                onChange={(e) => onChange({ initialCapital: e.target.value })}
                placeholder="用來算總報酬率"
              />
            </div>
          </Section>

          <label className="journal-mistake-check">
            <input type="checkbox" checked={form.aiEnabled} onChange={(e) => onChange({ aiEnabled: e.target.checked })} />
            允許 AI 依市場資料給建議與復盤
          </label>

          {form.kind === "ai" ? (
            <>
              <label className="journal-mistake-check">
                <input
                  type="checkbox"
                  checked={form.simulationEnabled}
                  onChange={(e) =>
                    onChange({
                      simulationEnabled: e.target.checked,
                      aiEnabled: e.target.checked ? true : form.aiEnabled,
                    })
                  }
                />
                啟用 AI 交易員（自動投資模擬）
              </label>
              <Hint>
                交易日固定排程：美東開盤前 30 分鐘研究一次；盤中依設定間隔決策；收盤後復盤一次。週末與休市日不執行這三種分析，但每日產業報告仍固定產出並保存歷史。
                產業報告會整合分析師共識、國會公開交易披露與政策訊號；未設定 FMP / Finnhub Key 時會明示國會資料缺口。
              </Hint>

              <Section title="AI 模型">
                {providers.length === 0 ? (
                  <p className="journal-form-warn">請先在「設定」頁填入 AI API Key，才能選 Provider 與模型。</p>
                ) : null}
                <div className="grid g2">
                  <div className="settings-field">
                    <label>AI Provider</label>
                    <select
                      value={form.aiProvider || providers[0]?.id || ""}
                      onChange={(e) => onChange({ aiProvider: e.target.value, aiModel: "" })}
                    >
                      <option value="">使用全域預設</option>
                      {providers.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.label}
                        </option>
                      ))}
                    </select>
                    <Hint>此帳號專用的 AI 後端；留空則跟隨 App 全域設定。</Hint>
                  </div>
                  <div className="settings-field">
                    <label>模型</label>
                    <select
                      value={effectiveModel}
                      disabled={modelsQ.isLoading || modelOptions.length === 0}
                      onChange={(e) => onChange({ aiModel: e.target.value })}
                    >
                      {modelOptions.length === 0 ? (
                        <option value="">{modelsQ.isLoading ? "載入模型中…" : defaultModel || "無可用模型"}</option>
                      ) : (
                        modelOptions.map((m) => (
                          <option key={m.id} value={m.id}>
                            {m.id}
                          </option>
                        ))
                      )}
                    </select>
                    <Hint>盤前研究、每日產業報告、盤中決策與盤後復盤都會用此模型。</Hint>
                  </div>
                </div>
              </Section>

              {form.simulationEnabled ? (
                <Section title="自動投資行為">
                  <div className="grid g2">
                    <div className="settings-field">
                      <label>盤中輪詢間隔</label>
                      <select
                        value={form.simulationIntervalMin}
                        onChange={(e) => onChange({ simulationIntervalMin: e.target.value })}
                      >
                        <option value="15">每 15 分鐘</option>
                        <option value="30">每 30 分鐘</option>
                        <option value="60">每 1 小時</option>
                        <option value="120">每 2 小時</option>
                      </select>
                      <Hint>僅在交易時段內，依此間隔自動跑一輪盤中決策（可買賣）。</Hint>
                    </div>
                    <div className="settings-field">
                      <label>交易市場</label>
                      <select
                        value={form.simulationMarket}
                        onChange={(e) => onChange({ simulationMarket: e.target.value })}
                      >
                        <option value="US">美股（盤前 9:00–9:30 · 盤中 9:30–16:00 · 盤後 16:00–16:30 ET）</option>
                        <option value="ANY">美股優先，台股盤中亦可</option>
                        <option value="TW">僅台股（9:00–13:30）</option>
                      </select>
                      <Hint>美股盤前與盤後窗口內各只執行一次；定期輪詢只會在盤中執行。</Hint>
                    </div>
                  </div>

                  <div className="settings-field">
                    <label>標的範圍</label>
                    <select
                      value={form.universeMode}
                      onChange={(e) => onChange({ universeMode: e.target.value as UniverseMode })}
                    >
                      <option value="watchlist">追蹤清單（watchlist）</option>
                      <option value="ai_pick">AI 自選標的</option>
                      <option value="custom">自訂代號清單</option>
                    </select>
                    <Hint>{universeBehavior}</Hint>
                  </div>

                  {form.universeMode === "custom" ? (
                    <div className="settings-field">
                      <label>自訂代號（逗號分隔）</label>
                      <input
                        value={form.universeCustom}
                        onChange={(e) => onChange({ universeCustom: e.target.value })}
                        placeholder="NVDA,AAPL,2330.TW"
                      />
                    </div>
                  ) : null}

                  <TraderPersonalityPicker
                    personalityId={form.traderPersonality}
                    strategyText={form.simulationStrategy}
                    onSelect={(id, strategy, defaults) =>
                      onChange({
                        traderPersonality: id,
                        simulationStrategy: strategy,
                        traderConfig: id === "custom"
                          ? { ...form.traderConfig, paramOverrides: form.traderConfig.paramOverrides || {} }
                          : { ...DEFAULT_TRADER_CONFIG, paramOverrides: {} },
                        ...(defaults?.simulationIntervalMin
                          ? { simulationIntervalMin: String(defaults.simulationIntervalMin) }
                          : {}),
                      })
                    }
                    onStrategyChange={(simulationStrategy) => onChange({ simulationStrategy })}
                    customConfig={form.traderConfig}
                    onCustomConfigChange={(traderConfig) => onChange({ traderConfig })}
                    onAccountParamChange={(key, value) => onChange({ [key]: value })}
                    accountParamValues={{ simulationIntervalMin: form.simulationIntervalMin }}
                  />
                </Section>
              ) : null}
            </>
          ) : null}

          <div className="settings-field">
            <label>備註</label>
            <textarea
              className="skill-notes-textarea"
              rows={2}
              value={form.note}
              onChange={(e) => onChange({ note: e.target.value })}
            />
          </div>
          {editing && purge ? (
            <div className="account-delete-box">
              <div className="account-delete-head">
                <strong className="small">刪除帳號</strong>
                {purge.needsForce ? (
                  <span className="small muted">
                    含 {purge.tradeCount} 筆交易、{purge.runCount} 筆模擬、{purge.memoryCount} 筆 AI 記憶
                  </span>
                ) : (
                  <span className="small muted">此帳號無模擬資料，可直接刪除</span>
                )}
              </div>
              {purge.needsForce ? (
                <label className="account-delete-force small">
                  <input
                    type="checkbox"
                    checked={deleteForce}
                    onChange={(e) => setDeleteForce(e.target.checked)}
                  />
                  一併刪除所有交易、模擬紀錄與復盤記憶（無法復原）
                </label>
              ) : null}
              {!purge.canDelete && purge.blockReason ? (
                <p className="small" style={{ color: "var(--crimson)", margin: "6px 0 0" }}>
                  {purge.blockReason}
                </p>
              ) : null}
              {deleteError ? (
                <p className="small" style={{ color: "var(--crimson)", margin: "6px 0 0" }}>
                  {deleteError}
                </p>
              ) : null}
            </div>
          ) : null}
        </div>
        <div className="journal-form-footer">
          {saveBlockReason ? <p className="journal-form-save-hint">{saveBlockReason}</p> : null}
          <div className="settings-actions">
            {editing && onDelete && purge?.canDelete ? (
              <button
                type="button"
                className="btn-ghost danger"
                disabled={saving || (purge.needsForce && !deleteForce)}
                onClick={() => onDelete({ force: deleteForce || !purge.needsForce })}
              >
                刪除帳號
              </button>
            ) : (
              <span />
            )}
            <div className="journal-form-actions">
              <button type="button" className="btn-ghost" disabled={saving} onClick={onClose}>
                取消
              </button>
              <button type="button" className="btn-primary" disabled={!canSave} onClick={onSave}>
                {saving ? "儲存中…" : "儲存"}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export function accountPayloadFromForm(form: AccountForm) {
  const num = (s: string) => (s.trim() === "" ? null : Number(s));
  const initialCapital = num(form.initialCapital);
  let cash = num(form.cash) ?? 0;
  if (form.kind === "ai" && form.simulationEnabled && initialCapital && cash === 0) {
    cash = initialCapital;
  }
  const simulationUniverse =
    form.universeMode === "custom"
      ? form.universeCustom.trim() || "watchlist"
      : form.universeMode;

  return {
    name: form.name.trim(),
    kind: form.kind,
    cash,
    initialCapital,
    aiEnabled: form.aiEnabled,
    simulationEnabled: form.kind === "ai" ? form.simulationEnabled : false,
    simulationIntervalMin: Number(form.simulationIntervalMin) || 30,
    simulationMarket: form.simulationMarket || "ANY",
    simulationUniverse,
    simulationOnlyMarketHours: form.simulationOnlyMarketHours,
    aiProvider: form.aiProvider.trim() || null,
    aiModel: form.aiModel.trim() || null,
    traderPersonality: form.kind === "ai" && form.simulationEnabled ? form.traderPersonality || "custom" : null,
    traderConfig: form.kind === "ai" && form.simulationEnabled
      ? form.traderPersonality === "custom"
        ? form.traderConfig
        : { paramOverrides: form.traderConfig.paramOverrides || {} }
      : null,
    simulationStrategy:
      form.kind === "ai" && form.simulationEnabled ? form.simulationStrategy.trim() || null : null,
    note: form.note.trim() || null,
  };
}
