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

function healthClass(h: string) {
  if (h === "ready") return "up";
  if (h === "blocked") return "down";
  if (h === "warn") return "warn";
  return "cool";
}

function fmtTime(iso?: string | null) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("zh-TW", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
  } catch {
    return iso.slice(0, 16);
  }
}

export function TraderStatusPanel({ status }: { status?: TraderOperationalStatus | null }) {
  if (!status) return null;

  return (
    <div className={`trader-status-panel trader-status-panel--${healthClass(status.health)}`}>
      <div className="trader-status-head">
        <strong className="small">AI 運作狀態</strong>
        <span className={`trader-status-pill trader-status-pill--${healthClass(status.health)}`}>
          {status.healthLabel}
        </span>
      </div>

      <div className="trader-status-grid small">
        <div>
          <span className="k">AI 連線</span>
          <span className="v">{status.aiReady ? `${status.aiProvider || "預設"} / ${status.aiModel || "預設模型"}` : "未就緒"}</span>
        </div>
        <div>
          <span className="k">自動模擬</span>
          <span className="v">{status.simulationEnabled ? "已開啟（排程會跑）" : "未開啟（僅手動）"}</span>
        </div>
        <div>
          <span className="k">今日市場</span>
          <span className="v">{status.tradingDay === false ? "休市，只做產業研究" : "交易日"}</span>
        </div>
        <div>
          <span className="k">今日開盤前</span>
          <span className="v">{status.today.preReport ? "已完成" : "尚未"}</span>
        </div>
        <div>
          <span className="k">每日產業報告</span>
          <span className="v">{status.today.industryReport ? "已產出" : "尚未"}</span>
        </div>
        <div>
          <span className="k">今日盤中</span>
          <span className="v">
            {status.today.intradayRuns} 輪
            {status.today.intradayReviews ? ` · 復盤 ${status.today.intradayReviews}` : ""}
          </span>
        </div>
        <div>
          <span className="k">上次執行</span>
          <span className="v">
            {status.lastRun
              ? `${status.lastRun.phase || "—"} / ${status.lastRun.status} · ${fmtTime(status.lastRun.at)}`
              : "尚無紀錄"}
          </span>
        </div>
        <div>
          <span className="k">固定排程</span>
          <span className="v">盤前一次 · 盤中每 N 分鐘 · 盤後一次</span>
        </div>
      </div>

      {status.lastRun?.error ? (
        <p className="small trader-status-error">上次錯誤：{status.lastRun.error}</p>
      ) : null}

      {status.blockers.length > 0 ? (
        <ul className="trader-status-blockers small">
          {status.blockers.map((b) => (
            <li key={b.code}>{b.message}</li>
          ))}
        </ul>
      ) : (
        <p className="small muted trader-status-note">{status.schedulerNote}</p>
      )}
    </div>
  );
}
