import { buildCommercialSnapshot } from "@/lib/commercial";
import type { Database } from "@/lib/store";
import LicenseHeartbeatPanel from "@/app/components/LicenseHeartbeatPanel";
import UpdatePanel from "@/app/components/UpdatePanel";

function fmtDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(date);
}

function tagClass(status: string) {
  if (status === "active" || status === "trial" || status === "completed" || status === "可用" || status === "正常" || status === "API 已绑定") return "green";
  if (status === "expired" || status === "suspended" || status === "failed" || status === "需处理") return "red";
  return "blue";
}

export default function CommercialOpsPanel({ db }: { db: Database }) {
  const snapshot = buildCommercialSnapshot(db);
  const usageRows = [
    { label: "趋势研究", value: snapshot.usage.trendResearches, limit: snapshot.riskLimits.dailyTrendResearches },
    { label: "Pin 发布", value: snapshot.usage.pinPublishes, limit: snapshot.riskLimits.dailyPinPublishes },
    { label: "图板创建", value: snapshot.usage.boardCreates, limit: snapshot.riskLimits.dailyBoardCreates },
    { label: "API 写入", value: snapshot.usage.apiWrites, limit: snapshot.riskLimits.dailyApiWrites },
  ];

  return (
    <>
      <div className="panel">
        <div className="panel-title">
          <div>
            <h3>商用授权</h3>
            <p className="muted">{snapshot.plan.label} · {snapshot.plan.monthlyPrice}</p>
          </div>
          <span className={`tag ${tagClass(snapshot.license.status)}`}>{snapshot.license.status}</span>
        </div>
        <div className="commercial-grid">
          <div>
            <strong>{snapshot.license.customerName}</strong>
            <div className="muted">客户</div>
          </div>
          <div>
            <strong>{fmtDate(snapshot.license.expiresAt)}</strong>
            <div className="muted">授权到期</div>
          </div>
          <div>
            <strong>{snapshot.license.seats}</strong>
            <div className="muted">席位</div>
          </div>
          <div>
            <strong>{snapshot.license.pinterestAccounts}</strong>
            <div className="muted">Pinterest 账号</div>
          </div>
        </div>
      </div>

      <div className="panel">
        <h3>今日额度</h3>
        <div className="usage-list">
          {usageRows.map((row) => (
            <div className="usage-item" key={row.label}>
              <div className="usage-head">
                <span>{row.label}</span>
                <strong>{row.value}/{row.limit}</strong>
              </div>
              <div className="usage-bar">
                <span style={{ width: `${row.limit ? Math.min(100, Math.round(row.value / row.limit * 100)) : 0}%` }} />
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="panel">
        <h3>模块状态</h3>
        <div className="list">
          {snapshot.modules.map((item) => (
            <div className="commercial-row" key={item.title}>
              <div>
                <strong>{item.title}</strong>
                <div className="muted">{item.detail}</div>
              </div>
              <span className={`tag ${tagClass(item.status)}`}>{item.status}</span>
            </div>
          ))}
        </div>
      </div>

      <LicenseHeartbeatPanel license={snapshot.license} remoteHeartbeat={snapshot.remoteHeartbeat} />
      <UpdatePanel />
    </>
  );
}
