import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  api,
  type TraderCustomConfig,
  type TraderPersonalityIndicators,
  type TraderPersonalityTemplate,
} from "../../lib/api";

type RiskLevel = TraderPersonalityTemplate["riskLevel"];

const RISK_THEME: Record<
  string,
  { accent: string; bg: string; bar: string; label: string }
> = {
  conservative: {
    accent: "var(--teal)",
    bg: "color-mix(in srgb, var(--teal) 14%, var(--panel))",
    bar: "var(--teal)",
    label: "保守",
  },
  moderate: {
    accent: "var(--gold-soft)",
    bg: "color-mix(in srgb, var(--gold) 12%, var(--panel))",
    bar: "var(--gold)",
    label: "均衡",
  },
  aggressive: {
    accent: "var(--crimson)",
    bg: "color-mix(in srgb, var(--crimson) 12%, var(--panel))",
    bar: "var(--crimson)",
    label: "進攻",
  },
  speculative: {
    accent: "var(--violet)",
    bg: "color-mix(in srgb, var(--violet) 14%, var(--panel))",
    bar: "var(--violet)",
    label: "投機",
  },
};

const BEHAVIOR_HINT: Record<string, string> = {
  buffett: "極少交易；大跌後分批買護城河公司，長期持有。",
  dalio: "分散配置、規則化再平衡；總經轉折時小步調倉。",
  lynch: "自下而上找成長股；PEG 合理、回檔加碼，財報驅動。",
  ptj: "順勢交易、嚴格止損；風報比 ≥2:1 才進場。",
  druckenmiller: "高信念時敢重倉；宏觀＋個股共振才出手。",
  soros: "抓反身性趨勢；快進快出，假設錯立刻撤。",
  livermore: "投機趨勢、關鍵點突破；賺了才加碼，絕不攤平。",
  custom: "完全由你定義風險、倉位與進出規則。",
};

const INDICATOR_LABELS: Record<keyof TraderPersonalityIndicators, string> = {
  macro: "總經",
  equity: "個股/基本面",
  technical: "技術面",
  sentiment: "情緒",
  derivatives: "衍生品/期貨",
  fixedIncome: "債券",
  commodities: "商品",
};

function riskTheme(level: RiskLevel) {
  return RISK_THEME[level] || RISK_THEME.moderate;
}

function riskBar(score: number, barColor: string) {
  const filled = Math.round(score);
  return (
    <div className="trader-risk-row">
      <span className="trader-risk-label">風險指數</span>
      <span className="trader-risk-bar" title={`${score}/10`}>
        {Array.from({ length: 10 }, (_, i) => (
          <span key={i} className={i < filled ? "on" : ""} style={i < filled ? { background: barColor } : undefined} />
        ))}
      </span>
      <span className="trader-risk-num">{score}/10</span>
    </div>
  );
}

function defaultsLine(t: TraderPersonalityTemplate) {
  return `單檔 ≤${t.defaults.maxPositionPct}% · 每輪 ≤${t.defaults.maxActionsPerRound} 筆 · ${t.defaults.simulationIntervalMin} 分鐘`;
}

function assetWeightLabel(w: string) {
  if (w === "primary") return "主";
  if (w === "secondary") return "輔";
  return "參考";
}

function ObservationList({ title, items }: { title: string; items: string[] }) {
  if (!items?.length) return null;
  return (
    <div className="trader-personality-obs-block">
      <h5>{title}</h5>
      <ul>
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

function IndicatorGrid({ indicators }: { indicators?: TraderPersonalityIndicators }) {
  if (!indicators) return null;
  const entries = Object.entries(indicators).filter(([, v]) => v?.length) as [
    keyof TraderPersonalityIndicators,
    string[],
  ][];
  if (!entries.length) return null;
  return (
    <div className="trader-personality-indicators">
      {entries.map(([key, items]) => (
        <div key={key} className="trader-personality-ind-group">
          <span className="trader-personality-ind-label">{INDICATOR_LABELS[key] || key}</span>
          <div className="trader-personality-ind-items">
            {items.map((item) => (
              <span key={item} className="trader-personality-ind-chip">
                {item}
              </span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function RulesList({ title, items }: { title: string; items?: string[] }) {
  if (!items?.length) return null;
  return (
    <div className="trader-personality-rules-block">
      <h5>{title}</h5>
      <ul>
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export function TraderPersonalityPicker({
  personalityId,
  strategyText,
  onSelect,
  onStrategyChange,
  customConfig,
  onCustomConfigChange,
  onAccountParamChange,
  accountParamValues,
}: {
  personalityId: string;
  strategyText: string;
  onSelect: (id: string, strategy: string, defaults?: TraderPersonalityTemplate["defaults"]) => void;
  onStrategyChange: (text: string) => void;
  customConfig: TraderCustomConfig;
  onCustomConfigChange: (config: TraderCustomConfig) => void;
  onAccountParamChange: (key: "simulationIntervalMin", value: string) => void;
  accountParamValues: { simulationIntervalMin: string };
}) {
  const [detailTab, setDetailTab] = useState<"watch" | "indicators" | "rules" | "params">("watch");
  const q = useQuery({
    queryKey: ["trader-personality-templates"],
    queryFn: api.traderPersonalityTemplates,
  });
  const templates = q.data?.templates || [];
  const selected = templates.find((t) => t.id === personalityId);
  const updateCustom = (patch: Partial<TraderCustomConfig>) => onCustomConfigChange({ ...customConfig, ...patch });
  const updateOverride = (key: string, value: string) => {
    onCustomConfigChange({
      ...customConfig,
      paramOverrides: { ...(customConfig.paramOverrides || {}), [key]: value },
    });
    if (key === "simulationIntervalMin") onAccountParamChange("simulationIntervalMin", value);
  };
  const paramDefault = (key: string, fallback?: string) => {
    if (key === "maxPositionPct") return String(selected?.defaults.maxPositionPct ?? "");
    if (key === "maxActionsPerRound") return String(selected?.defaults.maxActionsPerRound ?? "");
    if (key === "simulationIntervalMin") return accountParamValues.simulationIntervalMin || String(selected?.defaults.simulationIntervalMin ?? "");
    return fallback || "";
  };
  const updateList = (
    group: "observation" | "tradingRules",
    key: string,
    raw: string,
  ) => onCustomConfigChange({
    ...customConfig,
    [group]: {
      ...customConfig[group],
      [key]: raw.split("\n").map((line) => line.trim()).filter(Boolean),
    },
  });

  return (
    <div className="trader-personality-picker">
      <div className="trader-personality-intro">
        <strong>交易員性格模板</strong>
        <p>
          決定 AI 如何觀察市場（股票、債券、期貨、匯率、商品）與下單紀律。每個模板內建觀察清單、指標雷達、交易規則與可調參數，會寫入盤前/盤中/復盤提示詞。
        </p>
      </div>

      {q.isLoading ? <p className="trader-personality-loading">載入模板…</p> : null}

      <div className="trader-personality-grid">
        {templates.map((t) => {
          const active = t.id === personalityId;
          const theme = riskTheme(t.riskLevel);
          return (
            <button
              key={t.id}
              type="button"
              className={`trader-personality-card${active ? " active" : ""}`}
              style={
                {
                  "--tp-accent": theme.accent,
                  "--tp-bg": theme.bg,
                } as React.CSSProperties
              }
              onClick={() => {
                const nextStrategy = t.id === "custom" && strategyText.trim() ? strategyText : t.strategy;
                onSelect(t.id, nextStrategy, t.defaults);
              }}
            >
              {active ? <span className="trader-personality-selected-mark">已選</span> : null}
              <div className="trader-personality-card-head">
                <div>
                  <div className="trader-personality-name">{t.name}</div>
                  <div className="trader-personality-name-en">{t.nameEn}</div>
                </div>
                <span className="trader-risk-pill">{t.riskLabel}</span>
              </div>

              <p className="trader-personality-behavior">{BEHAVIOR_HINT[t.id] || t.strategyPreview}</p>

              {riskBar(t.riskScore, theme.bar)}

              <div className="trader-personality-defaults">{defaultsLine(t)}</div>

              <div className="trader-personality-tags">
                {t.tags.map((tag) => (
                  <span key={tag} className="trader-personality-tag">
                    {tag}
                  </span>
                ))}
              </div>
            </button>
          );
        })}
      </div>

      {selected ? (
        <div
          className="trader-personality-detail"
          style={{ "--tp-accent": riskTheme(selected.riskLevel).accent } as React.CSSProperties}
        >
          <div className="trader-personality-detail-head">
            <strong>{selected.name}</strong>
            <span className="trader-risk-pill">{selected.riskLabel}</span>
          </div>
          <p className="trader-personality-detail-behavior">{BEHAVIOR_HINT[selected.id]}</p>

          <div className="trader-personality-detail-stats">
            <div>
              <span className="k">單檔上限</span>
              <span className="v">≤{selected.defaults.maxPositionPct}%</span>
            </div>
            <div>
              <span className="k">每輪動作</span>
              <span className="v">≤{selected.defaults.maxActionsPerRound} 筆</span>
            </div>
            <div>
              <span className="k">盤中間隔</span>
              <span className="v">{selected.defaults.simulationIntervalMin} 分</span>
            </div>
          </div>

          {selected.assetClasses?.length ? (
            <div className="trader-personality-assets">
              <span className="trader-personality-assets-label">觀察資產</span>
              {selected.assetClasses.map((a) => (
                <span key={a.id} className={`trader-personality-asset-chip w-${a.weight}`} title={a.note}>
                  <em>{assetWeightLabel(a.weight)}</em> {a.label}
                </span>
              ))}
            </div>
          ) : null}

          <div className="trader-personality-detail-tabs" role="tablist" aria-label="模板詳情">
            {(
              [
                ["watch", "觀察清單"],
                ["indicators", "指標雷達"],
                ["rules", "交易規則"],
                ["params", "可調參數"],
              ] as const
            ).map(([id, label]) => (
              <button
                key={id}
                type="button"
                role="tab"
                aria-selected={detailTab === id}
                className={`trader-personality-detail-tab${detailTab === id ? " active" : ""}`}
                onClick={() => setDetailTab(id)}
              >
                {label}
              </button>
            ))}
          </div>

          {detailTab === "watch" && selected.observation ? (
            <div className="trader-personality-obs-grid">
              <ObservationList title="開盤前必查" items={selected.observation.preMarket} />
              <ObservationList title="盤中必盯" items={selected.observation.intraday} />
              <ObservationList title="盤後檢討" items={selected.observation.postMarket} />
            </div>
          ) : null}

          {detailTab === "indicators" ? <IndicatorGrid indicators={selected.indicators} /> : null}

          {detailTab === "rules" && selected.tradingRules ? (
            <div className="trader-personality-rules-grid">
              <RulesList title="進場" items={selected.tradingRules.entry} />
              <RulesList title="出場" items={selected.tradingRules.exit} />
              <RulesList title="倉位" items={selected.tradingRules.sizing} />
              <RulesList title="禁止" items={selected.tradingRules.forbidden} />
            </div>
          ) : null}

          {detailTab === "params" && selected.tunableParams?.length ? (
            <div className="trader-personality-params-table">
              <table>
                <thead>
                  <tr>
                    <th>參數</th>
                    <th>預設</th>
                    <th>設定位置</th>
                    <th>說明</th>
                  </tr>
                </thead>
                <tbody>
                  {selected.tunableParams.map((p) => (
                    <tr key={p.key}>
                      <td>
                        <strong>{p.label}</strong>
                        <span className="param-key">{p.key}</span>
                      </td>
                      <td>
                        {p.default != null || ["maxPositionPct", "maxActionsPerRound", "simulationIntervalMin"].includes(p.key) ? (
                          <input
                            className="trader-param-input"
                            value={customConfig.paramOverrides?.[p.key] ?? paramDefault(p.key, p.default)}
                            onChange={(event) => updateOverride(p.key, event.target.value)}
                            aria-label={`${p.label} 覆寫值`}
                          />
                        ) : <span className="muted">請於對應設定區調整</span>}
                      </td>
                      <td>{p.appliesTo === "account" ? "帳號設定" : "策略全文"}</td>
                      <td>{p.description}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : null}

          <p className="trader-personality-detail-note">
            輸入值會保存為此帳號專用覆寫，並注入 AI 提示詞；不會修改模板或其他交易員。
          </p>
        </div>
      ) : null}

      {personalityId === "custom" ? (
        <div className="trader-custom-console">
          <div className="trader-custom-head">
            <div>
              <strong>自訂交易員參數</strong>
              <p>這些不是展示文字；儲存後會直接限制下單並注入每次 AI Prompt。</p>
            </div>
            <span>STRUCTURED CONFIG</span>
          </div>

          <div className="trader-custom-number-grid">
            {([
              ["riskScore", "風險指數", 1, 10],
              ["maxPositionPct", "單檔上限 %", 1, 100],
              ["maxActionsPerRound", "每輪最多動作", 1, 10],
              ["maxOpenPositions", "最多持倉檔數", 1, 30],
              ["minCashReservePct", "最低現金 %", 0, 100],
            ] as const).map(([key, label, min, max]) => (
              <label key={key}>
                <span>{label}</span>
                <input
                  type="number"
                  min={min}
                  max={max}
                  value={customConfig[key]}
                  onChange={(event) => updateCustom({ [key]: Math.min(max, Math.max(min, Number(event.target.value) || min)) })}
                />
              </label>
            ))}
          </div>

          <div className="trader-custom-list-grid">
            <label>
              <span>開盤前必查（每行一項）</span>
              <textarea value={customConfig.observation.preMarket.join("\n")} onChange={(e) => updateList("observation", "preMarket", e.target.value)} />
            </label>
            <label>
              <span>盤中必盯（每行一項）</span>
              <textarea value={customConfig.observation.intraday.join("\n")} onChange={(e) => updateList("observation", "intraday", e.target.value)} />
            </label>
            <label>
              <span>盤後檢討（每行一項）</span>
              <textarea value={customConfig.observation.postMarket.join("\n")} onChange={(e) => updateList("observation", "postMarket", e.target.value)} />
            </label>
            <label>
              <span>進場規則（每行一項）</span>
              <textarea value={customConfig.tradingRules.entry.join("\n")} onChange={(e) => updateList("tradingRules", "entry", e.target.value)} />
            </label>
            <label>
              <span>出場規則（每行一項）</span>
              <textarea value={customConfig.tradingRules.exit.join("\n")} onChange={(e) => updateList("tradingRules", "exit", e.target.value)} />
            </label>
            <label>
              <span>倉位規則（每行一項）</span>
              <textarea value={customConfig.tradingRules.sizing.join("\n")} onChange={(e) => updateList("tradingRules", "sizing", e.target.value)} />
            </label>
            <label>
              <span>禁止事項（每行一項）</span>
              <textarea value={customConfig.tradingRules.forbidden.join("\n")} onChange={(e) => updateList("tradingRules", "forbidden", e.target.value)} />
            </label>
          </div>
        </div>
      ) : null}

      <div className="settings-field trader-personality-strategy-field">
        <label>性格與策略全文（可編輯）</label>
        <p className="journal-form-hint">
          直接餵給 AI。可覆寫停損%、PEG 上限、現金保留比例等；留空則用模板預設。帳號層級參數（標的範圍、盤中間隔）在「自動投資行為」區塊設定。
        </p>
        <textarea
          className="trader-personality-strategy-input"
          rows={9}
          value={strategyText}
          onChange={(e) => onStrategyChange(e.target.value)}
          placeholder="選模板後會帶入預設策略，你可依帳號風格修改…"
        />
      </div>
    </div>
  );
}
