import type { PositionBookPayload } from "../../lib/api";

function fmtMoney(v: number | null | undefined) {
  if (v == null || Number.isNaN(v)) return "—";
  const sign = v > 0 ? "+" : v < 0 ? "-" : "";
  return `${sign}$${Math.abs(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 fmtPrice(v: number | null | undefined) {
  if (v == null || Number.isNaN(v)) return "—";
  return `$${v.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
}

function statusClass(status: string) {
  if (status === "at_stop" || status === "overweight") return "danger";
  if (status === "near_stop" || status === "underwater") return "warn";
  if (status === "profitable") return "up";
  return "cool";
}

export function PositionBookPanel({ book }: { book?: PositionBookPayload | null }) {
  if (!book) return null;
  const { summary, limits, positions, sectorBreakdown, alerts } = book;

  return (
    <div className="position-book">
      <div className="position-book-summary">
        <div className="position-book-kpi">
          <span className="k">持倉檔數</span>
          <span className="v">
            {summary.openCount}
            <em> / {limits.maxOpenPositions}</em>
          </span>
        </div>
        <div className="position-book-kpi">
          <span className="k">最大單檔</span>
          <span className={`v${summary.maxWeightPct > limits.maxPositionPct ? " over" : ""}`}>
            {fmtPct(summary.maxWeightPct, 1)}
            <em> ≤{limits.maxPositionPct}%</em>
          </span>
        </div>
        <div className="position-book-kpi">
          <span className="k">前三集中度</span>
          <span className="v">{fmtPct(summary.top3ConcentrationPct, 1)}</span>
        </div>
        <div className="position-book-kpi">
          <span className="k">組合風險熱度</span>
          <span className="v" title="各倉停損風險加總佔總資產">
            {fmtPct(summary.portfolioHeatPct, 1)}
          </span>
        </div>
        <div className="position-book-kpi">
          <span className="k">現金保留</span>
          <span className={`v${summary.cashPct < limits.minCashReservePct ? " under" : ""}`}>
            {fmtPct(summary.cashPct, 1)}
            <em> ≥{limits.minCashReservePct}%</em>
          </span>
        </div>
        <div className="position-book-kpi">
          <span className="k">可用現金</span>
          <span className="v">{fmtMoney(summary.buyingPower)}</span>
        </div>
      </div>

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

      {sectorBreakdown?.length ? (
        <div className="position-book-sectors small muted">
          產業：
          {sectorBreakdown.map((s) => (
            <span key={s.sector} className="position-book-sector-chip">
              {s.sector} {s.weightPct.toFixed(1)}%
            </span>
          ))}
        </div>
      ) : null}

      {positions.length === 0 ? (
        <p className="small muted mt-s">目前無持倉。AI 盤中買進後會顯示完整倉位表。</p>
      ) : (
        <div className="position-book-table-wrap mt-s">
          <table className="position-book-table">
            <thead>
              <tr>
                <th>標的</th>
                <th>張數</th>
                <th>現價</th>
                <th>市值</th>
                <th>佔比</th>
                <th>浮盈虧</th>
                <th>停損</th>
                <th>目標</th>
                <th>風險%</th>
                <th>R:R</th>
                <th>狀態</th>
              </tr>
            </thead>
            <tbody>
              {positions.map((p) => (
                <tr key={p.symbol}>
                  <td>
                    <strong>{p.symbol}</strong>
                    {p.sector ? <span className="position-book-sector">{p.sector}</span> : null}
                    {p.holdDays != null ? <span className="position-book-hold">{p.holdDays} 天</span> : null}
                  </td>
                  <td>{p.shares ?? "—"}</td>
                  <td>{fmtPrice(p.price)}</td>
                  <td>{fmtMoney(p.value)}</td>
                  <td>{p.weightPct != null ? `${p.weightPct.toFixed(1)}%` : "—"}</td>
                  <td
                    style={{
                      color:
                        p.unrealizedPnl != null
                          ? p.unrealizedPnl >= 0
                            ? "var(--emerald)"
                            : "var(--crimson)"
                          : undefined,
                    }}
                  >
                    {p.unrealizedPnl != null ? fmtMoney(p.unrealizedPnl) : "—"}
                    {p.unrealizedPct != null ? ` (${fmtPct(p.unrealizedPct)})` : ""}
                  </td>
                  <td>
                    {fmtPrice(p.stopPrice)}
                    {p.distanceToStopPct != null ? (
                      <span className="position-book-dist"> -{p.distanceToStopPct}%</span>
                    ) : null}
                  </td>
                  <td>
                    {fmtPrice(p.targetPrice)}
                    {p.distanceToTargetPct != null ? (
                      <span className="position-book-dist"> +{p.distanceToTargetPct}%</span>
                    ) : null}
                  </td>
                  <td>{p.riskPct != null ? `${p.riskPct.toFixed(1)}%` : "—"}</td>
                  <td>{p.riskReward != null ? `${p.riskReward}:1` : "—"}</td>
                  <td>
                    <span className={`position-book-status position-book-status--${statusClass(p.status)}`}>
                      {p.statusLabel}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}