import type { TraderMemoryItem } from "../../lib/api";
import MarkdownMessage from "../MarkdownMessage";

type EntrySizing = {
  tradeId?: number;
  symbol?: string;
  shares?: number;
  price?: number;
  cost?: number;
  assetPct?: number;
};

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

function fmtEntryLine(e: EntrySizing) {
  const sym = e.symbol || "—";
  const shares = e.shares != null ? `${e.shares} 張` : "— 張";
  const price = e.price != null ? `@ ${fmtMoney(e.price)}` : "";
  const cost = e.cost != null ? `= ${fmtMoney(e.cost)}` : "";
  const pct = e.assetPct != null ? `· 佔資產 ${e.assetPct.toFixed(1)}%` : "";
  return `${sym} 進場 ${shares} ${price} ${cost} ${pct}`.replace(/\s+/g, " ").trim();
}

type MacroMeta = {
  regime?: string;
  summary?: string;
  drivers?: string[];
  risks?: string[];
};

type SectorRot = {
  etf?: string;
  name?: string;
  stance?: string;
  ret5d?: number;
  flow?: string;
  reason?: string;
};

type NewsItem = {
  headline?: string;
  sector?: string;
  symbols?: string[];
  impact?: string;
  note?: string;
};

function impactTone(impact?: string) {
  if (impact === "bullish") return "up";
  if (impact === "bearish") return "down";
  return "cool";
}

export function TraderAnalysisReport({ preReport }: { preReport?: TraderMemoryItem | null }) {
  if (!preReport) return null;
  const meta = (preReport.meta || {}) as {
    macro?: MacroMeta;
    sectorRotation?: SectorRot[];
    news?: NewsItem[];
  };
  const macro = meta.macro;
  const rotation = meta.sectorRotation || [];
  const news = meta.news || [];

  return (
    <div className="trader-analysis-report">
      <div className="small muted">{preReport.title || "市場分析報告"}</div>

      {macro ? (
        <section className="trader-report-section">
          <h4 className="small">美股總經</h4>
          {macro.regime ? (
            <span className="trader-report-pill">{macro.regime}</span>
          ) : null}
          {macro.summary ? <p className="small">{macro.summary}</p> : null}
          {macro.drivers?.length ? (
            <ul className="small trader-report-list">
              {macro.drivers.map((d) => (
                <li key={d}>{d}</li>
              ))}
            </ul>
          ) : null}
        </section>
      ) : null}

      {rotation.length > 0 ? (
        <section className="trader-report-section">
          <h4 className="small">板塊輪動</h4>
          <div className="trader-rotation-grid">
            {rotation.slice(0, 8).map((s) => (
              <div key={`${s.etf}-${s.name}`} className="trader-rotation-card">
                <div className="trader-rotation-head">
                  <strong className="small">{s.name || s.etf}</strong>
                  <span className="small muted">{s.stance || "—"}</span>
                </div>
                <p className="small muted">
                  {s.ret5d != null ? `5日 ${s.ret5d > 0 ? "+" : ""}${s.ret5d}%` : ""}
                  {s.flow ? ` · ${s.flow}` : ""}
                </p>
                {s.reason ? <p className="small">{s.reason}</p> : null}
              </div>
            ))}
          </div>
        </section>
      ) : null}

      {news.length > 0 ? (
        <section className="trader-report-section">
          <h4 className="small">重要新聞</h4>
          <div className="trader-news-list">
            {news.slice(0, 8).map((n, i) => (
              <div key={`${n.headline}-${i}`} className="trader-news-row">
                <span className={`trader-news-impact ${impactTone(n.impact)}`}>{n.impact || "—"}</span>
                <div>
                  <p className="small">{n.headline}</p>
                  <p className="small muted">
                    {[n.sector, ...(n.symbols || [])].filter(Boolean).join(" · ")}
                    {n.note ? ` — ${n.note}` : ""}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </section>
      ) : null}

      <section className="trader-report-section">
        <h4 className="small">完整報告</h4>
        <div className="editorial small trader-report-markdown">
          <MarkdownMessage text={`${preReport.body.slice(0, 3500)}${preReport.body.length > 3500 ? "…" : ""}`} />
        </div>
      </section>
    </div>
  );
}

export function TraderIntradayReviews({ reviews }: { reviews: TraderMemoryItem[] }) {
  if (!reviews.length) return null;
  return (
    <div className="journal-trader-block mt-s">
      <div className="small muted">盤中復盤（有買進即復盤）</div>
      {reviews.map((r) => {
        const meta = (r.meta || {}) as { entries?: EntrySizing[]; totalAssets?: number };
        const entries = meta.entries || [];
        return (
          <div key={r.id} className="trader-intraday-review">
            <div className="small muted">{r.title}</div>
            {entries.length > 0 ? (
              <div className="trader-entry-sizing mt-s">
                {entries.map((e) => (
                  <div key={`${e.tradeId ?? e.symbol}-${e.shares}`} className="trader-entry-sizing-row small">
                    <strong>{fmtEntryLine(e)}</strong>
                  </div>
                ))}
                {meta.totalAssets ? (
                  <div className="small muted" style={{ marginTop: 4 }}>
                    總資產 {fmtMoney(meta.totalAssets)}
                  </div>
                ) : null}
              </div>
            ) : null}
            <div className="editorial small trader-report-markdown" style={{ marginTop: 4 }}>
              <MarkdownMessage text={`${r.body.slice(0, 1500)}${r.body.length > 1500 ? "…" : ""}`} />
            </div>
          </div>
        );
      })}
    </div>
  );
}
