import { useMemo, useState } from "react";
import type { TraderFollowPayload, TraderFollowSignal } from "../../lib/api";

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

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

function verdictTone(v?: string | null): "up" | "down" | "cool" {
  if (v === "合理") return "up";
  if (v === "過度進取") return "down";
  return "cool";
}

function scaledShares(signal: TraderFollowSignal, myCapital: number | null) {
  if (!myCapital || myCapital <= 0 || !signal.assetPct || !signal.price || signal.price <= 0) return null;
  const targetCost = (myCapital * signal.assetPct) / 100;
  const shares = Math.floor(targetCost / signal.price);
  if (shares <= 0) return null;
  return {
    shares,
    cost: Math.round(shares * signal.price * 100) / 100,
    assetPct: signal.assetPct,
  };
}

function SignalCard({ signal, myCapital }: { signal: TraderFollowSignal; myCapital: number | null }) {
  const scaled = scaledShares(signal, myCapital);
  const tone = verdictTone(signal.verdict);
  const actionLabel = signal.type === "buy" ? "買進" : "賣出";

  return (
    <div className={`trader-follow-signal trader-follow-signal--${signal.type}`}>
      <div className="trader-follow-signal-head">
        <span className={`trader-follow-action trader-follow-action--${signal.type}`}>{actionLabel}</span>
        <strong>{signal.symbol}</strong>
        {signal.atLabel ? <span className="small muted">{signal.atLabel}</span> : null}
      </div>

      <div className="trader-entry-sizing-row small">
        <strong>
          {signal.shares != null ? `${signal.shares} 張` : "— 張"}
          {signal.price != null ? ` @ ${fmtMoney(signal.price)}` : ""}
          {signal.cost != null ? ` = ${fmtMoney(signal.cost)}` : ""}
          {signal.assetPct != null ? ` · 佔 AI 資產 ${signal.assetPct.toFixed(1)}%` : ""}
        </strong>
      </div>

      {(signal.stopPrice != null || signal.targetPrice != null || signal.riskReward != null) && (
        <div className="trader-follow-risk small muted">
          {signal.stopPrice != null ? <span>停損 {fmtMoney(signal.stopPrice)}</span> : null}
          {signal.targetPrice != null ? <span>目標 {fmtMoney(signal.targetPrice)}</span> : null}
          {signal.riskReward != null ? <span>風報比 {signal.riskReward}:1</span> : null}
        </div>
      )}

      {(signal.verdict || signal.alignmentScore != null) && (
        <div className="trader-follow-verdict small">
          {signal.verdict ? (
            <span className={`trader-follow-pill trader-follow-pill--${tone}`}>{signal.verdict}</span>
          ) : null}
          {signal.alignmentScore != null ? (
            <span className="small muted">對齊開盤前判斷 {signal.alignmentScore}/10</span>
          ) : null}
        </div>
      )}

      {signal.reason ? (
        <div className="small trader-follow-reason" style={{ whiteSpace: "pre-wrap" }}>
          {signal.reason}
        </div>
      ) : null}
      {signal.principle ? <p className="small muted">心法：{signal.principle}</p> : null}

      {scaled && signal.type === "buy" ? (
        <div className="trader-follow-scale small">
          若你本金 <strong>{fmtMoney(myCapital)}</strong> → 建議 <strong>{scaled.shares} 張</strong>
          （約 {fmtMoney(scaled.cost)}，同佔比 {scaled.assetPct.toFixed(1)}%）
        </div>
      ) : null}
    </div>
  );
}

export function TraderFollowPanel({ payload }: { payload?: TraderFollowPayload | null }) {
  const [myCapital, setMyCapital] = useState<string>("");

  const capitalNum = useMemo(() => {
    const n = Number(String(myCapital).replace(/,/g, ""));
    return Number.isFinite(n) && n > 0 ? n : null;
  }, [myCapital]);

  if (!payload) return null;
  const { trackRecord, signals, positionBook } = payload;
  const buys = signals.filter((s) => s.type === "buy");
  const sells = signals.filter((s) => s.type === "sell");

  return (
    <div className="journal-trader-block trader-follow-panel">
      <div className="trader-follow-head">
        <strong className="small">跟單依據</strong>
        <span className={`trader-follow-trust trader-follow-trust--${trackRecord.trustTone}`}>
          {trackRecord.trustLabel}
        </span>
      </div>

      <div className="trader-follow-stats small muted">
        {trackRecord.returnPct != null ? <span>總報酬 {fmtPct(trackRecord.returnPct)}</span> : null}
        {trackRecord.winRate != null ? <span>勝率 {trackRecord.winRate.toFixed(0)}%</span> : null}
        {trackRecord.closed > 0 ? <span>{trackRecord.closed} 筆已平倉</span> : <span>尚無平倉樣本</span>}
        {trackRecord.totalAssets != null ? <span>AI 總資產 {fmtMoney(trackRecord.totalAssets)}</span> : null}
        {positionBook?.summary ? (
          <span>
            持倉 {positionBook.summary.openCount}/{positionBook.limits.maxOpenPositions} 檔
            · 現金 {positionBook.summary.cashPct.toFixed(0)}%
            · 熱度 {positionBook.summary.portfolioHeatPct.toFixed(1)}%
          </span>
        ) : null}
      </div>

      {positionBook?.alerts?.length ? (
        <div className="trader-follow-alerts">
          {positionBook.alerts.map((a) => (
            <div key={a.message} className={`trader-follow-alert trader-follow-alert--${a.level}`}>
              {a.message}
            </div>
          ))}
        </div>
      ) : null}

      <p className="small muted">
        先看 AI 模擬績效，再決定是否跟。下方是今日結構化信號（張數、金額、佔比、判定），不必從長文復盤裡自己挖。
      </p>

      <div className="trader-follow-capital mt-s">
        <label className="small muted">你的本金（選填，換算建議張數）</label>
        <input
          type="number"
          className="bt-input"
          style={{ width: "100%", maxWidth: 200 }}
          placeholder="例：50000"
          value={myCapital}
          onChange={(e) => setMyCapital(e.target.value)}
        />
      </div>

      {signals.length === 0 ? (
        <p className="small muted mt-s">今日尚無盤中成交。跑「② 盤中一輪」且有買賣後，信號會出現在這裡。</p>
      ) : (
        <div className="trader-follow-signals mt-s">
          <div className="small muted">
            今日信號 {signals.length} 筆
            {buys.length ? ` · 買 ${buys.length}` : ""}
            {sells.length ? ` · 賣 ${sells.length}` : ""}
          </div>
          {signals.map((s) => (
            <SignalCard key={s.id} signal={s} myCapital={capitalNum} />
          ))}
        </div>
      )}
    </div>
  );
}