import { useMemo } from "react";
import type { TradeAccount, TradeDashboardPayload } from "../../lib/api";
import { Card } from "../ui";
import { AppIcon } from "../PixelIcons";
import EquityChart from "../EquityChart";
import { CHART } from "../../lib/chartPalette";
import { SimulationPanel } from "./SimulationPanel";
import { PositionBookPanel } from "./PositionBookPanel";

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 AllocationBar({ label, pct, color, value }: { label: string; pct: number; color: string; value: string }) {
  return (
    <div className="journal-alloc-row">
      <div className="journal-alloc-head">
        <span>{label}</span>
        <span className="muted small">
          {fmtPct(pct)} · {value}
        </span>
      </div>
      <div className="journal-alloc-track">
        <div className="journal-alloc-fill" style={{ width: `${Math.min(100, Math.max(0, pct))}%`, background: color }} />
      </div>
    </div>
  );
}

export function JournalDashboard({
  dash,
  accounts,
  accountId,
  onAccountChange,
  onEditAccount,
  onAddAccount,
  onAiReview,
  aiLoading,
  onSimulatePhase,
  simLoading,
}: {
  dash: TradeDashboardPayload;
  accounts: TradeAccount[];
  accountId: number;
  onAccountChange: (id: number) => void;
  onEditAccount: () => void;
  onAddAccount: () => void;
  onAiReview?: () => void;
  aiLoading?: boolean;
  onSimulatePhase?: (phase: string) => void;
  simLoading?: boolean;
}) {
  const annualChart = useMemo(
    () =>
      dash.annualPnl.map((y) => ({
        date: `${y.year}-12-31`,
        val: y.pnl,
      })),
    [dash.annualPnl],
  );

  const account = dash.account;

  return (
    <>
      <div className="journal-account-bar">
        <div className="journal-account-tabs">
          {accounts.map((a) => (
            <button
              key={a.id}
              type="button"
              className={`journal-account-tab${a.id === accountId ? " active" : ""}`}
              style={{ "--acc-color": a.color || "var(--gold)" } as React.CSSProperties}
              onClick={() => onAccountChange(a.id)}
            >
              <span className="journal-account-dot" />
              {a.name}
              {a.kind === "ai" ? <span className="journal-account-badge">AI</span> : null}
            </button>
          ))}
          <button type="button" className="journal-account-tab add" onClick={onAddAccount}>
            ＋ 帳號
          </button>
        </div>
        <div className="journal-account-actions">
          <button type="button" className="btn-ghost sm" onClick={onEditAccount}>
            現金 / 設定
          </button>
          {account.aiEnabled && onAiReview ? (
            <button type="button" className="btn-primary sm" disabled={aiLoading} onClick={onAiReview}>
              {aiLoading ? "分析中…" : "AI 今日復盤"}
            </button>
          ) : null}
        </div>
      </div>

      <div className="grid g4">
        <div className="card kpi">
          <div
            className="k-v"
            style={{
              color:
                dash.totalPnl > 0 ? "var(--emerald)" : dash.totalPnl < 0 ? "var(--crimson)" : undefined,
            }}
          >
            {fmtMoney(dash.totalPnl)}
          </div>
          <div className="k-l">總損益</div>
          <div className="k-d small muted">
            已實現 {fmtMoney(dash.realizedPnl)}
            {dash.unrealizedPnl ? ` · 未實現 ${fmtMoney(dash.unrealizedPnl)}` : ""}
          </div>
        </div>
        <div className="card kpi">
          <div className="k-v">{fmtMoney(dash.allocation.total)}</div>
          <div className="k-l">總資產</div>
          <div className="k-d small muted">
            股票 {fmtPct(dash.allocation.stockPct, 0)} · 現金 {fmtPct(dash.allocation.cashPct, 0)}
          </div>
        </div>
        <div className="card kpi">
          <div
            className="k-v"
            style={{
              color:
                dash.returnPct != null && dash.returnPct >= 0
                  ? "var(--emerald)"
                  : dash.returnPct != null
                    ? "var(--crimson)"
                    : undefined,
            }}
          >
            {dash.returnPct != null ? fmtPct(dash.returnPct) : "—"}
          </div>
          <div className="k-l">總報酬率</div>
          <div className="k-d small muted">
            {account.initialCapital != null ? `本金 $${account.initialCapital.toLocaleString()}` : "可設初始本金"}
          </div>
        </div>
        <div className="card kpi">
          <div className="k-v" style={{ color: "var(--emerald)" }}>
            {dash.stats.winRate != null ? `${dash.stats.winRate.toFixed(0)}%` : "—"}
          </div>
          <div className="k-l">勝率</div>
          <div className="k-d small muted">{dash.stats.closed} 筆已平倉</div>
        </div>
      </div>

      {account.kind === "ai" ? (
        <SimulationPanel
          account={account}
          onRunPhase={(p) => onSimulatePhase?.(p)}
          running={simLoading}
          returnPct={dash.returnPct}
          totalPnl={dash.totalPnl}
        />
      ) : null}

      <div className="grid g2 mt">
        <Card title="專業倉位簿" ico={<AppIcon name="coin" size={22} framed variant="nav" />}>
          {account.kind === "ai" && account.simulationEnabled ? (
            <p className="small muted" style={{ marginBottom: 8 }}>
              持倉報價與盈虧每分鐘刷新；含停損、目標、風險%、組合熱度與性格風控對照。
            </p>
          ) : null}
          <AllocationBar
            label="股票持倉"
            pct={dash.allocation.stockPct}
            color="var(--sky)"
            value={fmtMoney(dash.allocation.stockValue)}
          />
          <AllocationBar
            label="現金"
            pct={dash.allocation.cashPct}
            color="var(--gold)"
            value={fmtMoney(dash.allocation.cash)}
          />
          <PositionBookPanel book={dash.positionBook} />
        </Card>

        <Card title="年度損益" ico={<AppIcon name="chart" size={22} framed variant="nav" />}>
          {annualChart.length === 0 ? (
            <p className="muted small">尚無已平倉紀錄，平倉後會依出場年份彙總。</p>
          ) : (
            <>
              <EquityChart
                series={[{ name: "年度損益", color: CHART.gold, points: annualChart }]}
                heightClass="equity-chart equity-chart-sm"
              />
              <div className="dl mt-s">
                {dash.annualPnl.map((y) => (
                  <div className="row" key={y.year}>
                    <span className="k">{y.year}</span>
                    <span
                      className="v"
                      style={{ color: y.pnl >= 0 ? "var(--emerald)" : "var(--crimson)", fontWeight: 700 }}
                    >
                      {fmtMoney(y.pnl)} · {y.trades} 筆
                    </span>
                  </div>
                ))}
              </div>
            </>
          )}
        </Card>
      </div>

      {dash.equityCurve.length > 1 ? (
        <Card title="累積損益走勢" ico={<AppIcon name="flow" size={22} framed variant="nav" />} className="mt">
          <EquityChart
            series={[{ name: "累積損益", color: CHART.teal, points: dash.equityCurve }]}
            heightClass="equity-chart"
          />
        </Card>
      ) : null}

      {account.kind !== "ai" && !account.aiEnabled ? (
        <p className="small muted mt">
          此帳號未啟用 AI。在「現金 / 設定」中可開啟 AI 復盤，或新增 AI 模擬帳號比較績效。
        </p>
      ) : null}
    </>
  );
}
