import type { ReactElement } from "react";
import { useState } from "react";

import type { LiveProbePayload, LiveSurface } from "../../types/domain";
import { formatBeijingTime, shortToken, toneClass } from "../../utils";
import { StateTag } from "../shared/StateTag";
import { WorkbenchDialog } from "../shared/WorkbenchDialog";

interface WorkbenchProbeProps {
  live: LiveSurface | null;
}

interface ProbeRow {
  key: string;
  label: string;
  method?: string;
  path: string;
  result: LiveProbePayload | null | undefined;
  status: "ok" | "pending" | "blocked" | "source" | "warn";
  detail: string;
  lastCheckedAt: string | null;
}

interface ProbeResult {
  ok: boolean;
  status: number;
  data: LiveProbePayload | null;
  error: string | null;
}

export function WorkbenchProbe({ live }: WorkbenchProbeProps): ReactElement {
  const [open, setOpen] = useState(false);
  const rows: ProbeRow[] = [
    rowFromProbe("cloud-api-live", "Cloud API 实况身份", "GET", "/health/live", live?.healthLive ?? null),
    rowFromProbe("cloud-api-health", "Cloud API health", "GET", "/health", live?.health ?? null),
    rowFromProbe("rest-index", "REST index", "GET", "/v1", live?.restIndex ?? null),
    rowFromProbe("adapter", "Codex app-server adapter", "POST", "/v1/rpc/system.health", live?.adapter ?? null)
  ];
  const tone = rows.every((row) => row.status === "ok") ? "ok" : rows.some((row) => row.status === "blocked") ? "blocked" : "pending";
  const okCount = rows.filter((row) => row.status === "ok").length;
  const checkedAt = live?.loadedAt ? formatBeijingTime(live.loadedAt, { withSeconds: true }) : "未观测";
  return (
    <section className={`probe-card probe-card-compact probe-card-${tone} tone-border-${toneClass(tone)}`} data-probe-card>
      <button className="status-chip-button probe-summary-button" type="button" aria-haspopup="dialog" onClick={() => setOpen(true)}>
        <span className="status-chip-label">工作区状态</span>
        <StateTag tone={toneClass(tone)} data-probe-card-tone>{tone === "ok" ? "健康" : tone === "blocked" ? "阻塞" : "等待验证"}</StateTag>
        <span className="status-chip-meta">{okCount}/{rows.length} · {checkedAt}</span>
      </button>
      {open ? (
        <WorkbenchDialog id="probe-status-dialog" title="工作区状态明细" onClose={() => setOpen(false)}>
          <ul className="probe-list probe-list-dialog" role="list">
            {rows.map((row) => <ProbeListItem key={row.key} row={row} />)}
          </ul>
        </WorkbenchDialog>
      ) : null}
    </section>
  );
}

function ProbeListItem({ row }: { row: ProbeRow }): ReactElement {
  return (
    <li className="probe-row" role="listitem" data-probe-row={row.key}>
      <div className="probe-row-head">
        <span className={`probe-tone tone-${toneClass(row.status)}`} aria-hidden="true">●</span>
        <span className="probe-row-label">{row.label}</span>
        <span className={`probe-row-status tone-${toneClass(row.status)}`}>{row.status === "ok" ? "通过" : row.status === "blocked" ? "阻塞" : "等待"}</span>
      </div>
      <div className="probe-row-meta">
        <span className="probe-row-method">{row.method}</span>
        <span className="probe-row-path mono">{row.path}</span>
        <span className="probe-row-time">{row.lastCheckedAt ? formatBeijingTime(row.lastCheckedAt, { withSeconds: true }) : "未观测"}</span>
      </div>
      <p className="probe-row-detail">{row.detail}</p>
    </li>
  );
}

function rowFromProbe(key: string, label: string, method: string, path: string, probe: ProbeResult | null): ProbeRow {
  const data = probe?.data ?? null;
  const ok = Boolean(probe?.ok) && (data?.ready === true || data?.status === "ok" || data?.status === "ready");
  const lastCheckedAt = typeof data?.observedAt === "string" ? data.observedAt : null;
  const status: ProbeRow["status"] = ok
    ? "ok"
    : probe?.ok === false
      ? probe.status >= 500 ? "blocked" : "warn"
      : probe === null
        ? "pending"
        : "warn";
  return {
    key,
    label,
    method,
    path,
    result: data,
    status,
    detail: detailFor(probe, data, path),
    lastCheckedAt
  };
}

function detailFor(probe: ProbeResult | null, data: LiveProbePayload | null, path: string): string {
  if (!probe) return `等待 ${path} 实时元数据`;
  if (!probe.ok) return probe.error ?? `${path} HTTP ${probe.status}`;
  if (!data) return `${path} 响应为空`;
  const revision = typeof data.revision === "string" ? data.revision : null;
  const serviceId = typeof data.serviceId === "string" ? data.serviceId : null;
  const ready = data.ready === true ? "ready=true" : "ready=false";
  if (serviceId && revision) return `service=${serviceId}; env=${data.environment ?? "unknown"}; ${ready}; revision=${shortToken(revision, 12)}`;
  return `service=${serviceId ?? "unknown"}; ${ready}`;
}
