import React from "react";
import { fmtClock, fmtDate } from "./time";
import { LoadingTitle } from "./loading-indicator";
import { errorMessage, requestJson } from "./unidesk-error";
import { UniDeskErrorBanner } from "./unidesk-error-banner";

type AnyRecord = Record<string, any>;

const h = React.createElement;
const { useEffect, useMemo } = React;
const useState: any = React.useState;

function StatusBadge({ status, children, title }: AnyRecord) {
  const normalized = String(status || "unknown").toLowerCase();
  return h("span", { className: `status-badge ${normalized}`, title }, children || status || "unknown");
}

function MetricCard({ label, value, hint, tone }: AnyRecord) {
  return h("article", { className: `metric-card ${tone || ""}` },
    h("div", { className: "metric-label" }, label),
    h("div", { className: "metric-value" }, value),
    h("div", { className: "metric-hint" }, hint),
  );
}

function Panel({ title, eyebrow, actions, children, className, loading }: AnyRecord) {
  return h("section", { className: `panel ${className || ""}` },
    h("div", { className: "panel-head" },
      h("div", null,
        eyebrow ? h("p", { className: "panel-eyebrow" }, eyebrow) : null,
        h(LoadingTitle, { title, loading }),
      ),
      actions ? h("div", { className: "panel-actions" }, actions) : null,
    ),
    h("div", { className: "panel-body" }, children),
  );
}

function RawButton({ title, data, onOpen, testId }: AnyRecord) {
  return h("button", { type: "button", className: "ghost-btn", "data-testid": testId, onClick: () => onOpen?.(title, data) }, "查看原始JSON");
}

function EmptyState({ title, text }: AnyRecord) {
  return h("div", { className: "empty-state" }, h("strong", null, title), h("span", null, text));
}

function asArray(value: any): any[] {
  return Array.isArray(value) ? value : [];
}

function objectRecord(value: any): AnyRecord {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}

function microserviceRuntime(service: any): AnyRecord {
  return service?.runtime && typeof service.runtime === "object" && !Array.isArray(service.runtime) ? service.runtime : {};
}

function proxy(apiBaseUrl: string, path: string): string {
  return `${apiBaseUrl}/microservices/k3sctl-adapter/proxy${path}`;
}

function findAdapter(microservices: any[]): any | null {
  return microservices.find((service) => String(service?.id || "") === "k3sctl-adapter") || null;
}

function instanceTone(instance: any): string {
  if (instance?.healthy === true) return "online";
  if (String(instance?.role || "") === "standby") return "warn";
  return "failed";
}

function serviceTone(service: any): string {
  return service?.healthy === true ? "online" : "failed";
}

function fmtBool(value: any): string {
  if (value === true) return "YES";
  if (value === false) return "NO";
  return "--";
}

function clusterNodes(services: any[]): string[] {
  return Array.from(new Set(services.flatMap((service) => asArray(service?.expectedNodeIds).map((node) => String(node))))).filter(Boolean).sort();
}

function primaryInstance(services: any[]): string {
  const codeQueue = services.find((service) => service?.id === "code-queue") || services[0];
  return String(codeQueue?.activeInstanceId || "--");
}

function renderInstanceCard(instance: any) {
  return h("article", { key: instance?.id || instance?.nodeId, className: "k3s-instance-card" },
    h("div", { className: "node-card-head" },
      h("strong", null, instance?.nodeId || instance?.id || "--"),
      h(StatusBadge, { status: instanceTone(instance) }, instance?.healthy ? "HEALTHY" : "DEGRADED"),
    ),
    h("div", { className: "k3s-instance-role" },
      h("span", null, String(instance?.role || "worker").toUpperCase()),
      h("code", null, instance?.id || "--"),
    ),
      h("dl", { className: "k3s-kv" },
      h("dt", null, "Base URL"), h("dd", null, h("code", null, instance?.baseUrl || "--")),
      h("dt", null, "Proxy"), h("dd", null, instance?.proxyMode || "--"),
      h("dt", null, "Health"), h("dd", null, `${instance?.upstreamStatus ?? "--"} / ${instance?.status || "unknown"}`),
      h("dt", null, "Checked"), h("dd", null, fmtDate(instance?.checkedAt)),
    ),
  );
}

function renderManagedService(service: any, onRaw: any) {
  const instances = asArray(service?.instances);
  const active = objectRecord(service?.active);
  return h(Panel, {
    key: service?.id || "service",
    title: service?.id || "managed-service",
    eyebrow: `${service?.namespace || "unidesk"} / k3s managed service`,
    className: "k3s-service-panel",
    actions: h(RawButton, { title: `k3s service ${service?.id || ""}`, data: service, onOpen: onRaw, testId: `raw-k3s-service-${service?.id || "unknown"}` }),
  },
    h("div", { className: "k3s-service-summary" },
      h("div", null, h("span", null, "状态"), h(StatusBadge, { status: serviceTone(service) }, service?.status || "unknown")),
      h("div", null, h("span", null, "Active"), h("strong", null, service?.activeInstanceId || "--")),
      h("div", null, h("span", null, "Single Writer"), h("strong", null, fmtBool(service?.singleWriter))),
      h("div", null, h("span", null, "Active Health"), h("strong", null, active?.upstreamStatus ?? "--")),
    ),
    instances.length === 0
      ? h(EmptyState, { title: "暂无 k3s 实例", text: "adapter 没有返回该服务的 endpoint 列表" })
      : h("div", { className: "k3s-instance-grid" }, instances.map(renderInstanceCard)),
  );
}

export function K3sCtlPage({ microservices, onRaw, apiBaseUrl, onNavigate }: AnyRecord) {
  const adapter = findAdapter(Array.isArray(microservices) ? microservices : []);
  const runtime = microserviceRuntime(adapter);
  const [state, setState] = useState({ loading: false, error: "", data: null as any, refreshedAt: null as Date | null });

  async function load(): Promise<void> {
    setState((previous: any) => ({ ...previous, loading: true, error: "" }));
    try {
      const data = await requestJson(proxy(apiBaseUrl, "/api/control-plane"));
      setState({ loading: false, error: "", data, refreshedAt: new Date() });
    } catch (err) {
      setState((previous: any) => ({ ...previous, loading: false, error: errorMessage(err, "加载 k3s 控制平面失败") }));
    }
  }

  useEffect(() => { void load(); }, [apiBaseUrl]);

  const services = useMemo(() => asArray(state.data?.services), [state.data]);
  const nodes = clusterNodes(services);
  const healthyServices = services.filter((service) => service?.healthy === true).length;
  const totalInstances = services.reduce((sum, service) => sum + asArray(service?.instances).length, 0);
  const healthyInstances = services.reduce((sum, service) => sum + asArray(service?.instances).filter((instance) => instance?.healthy === true).length, 0);
  const primary = primaryInstance(services);
  const kubectl = objectRecord(state.data?.kubectl);
  const kubeProxy = objectRecord(state.data?.kubeApiProxy);
  const manifestPaths = asArray(state.data?.manifestPaths).map((item) => String(item));

  if (!adapter) return h(EmptyState, { title: "k3sctl-adapter 未登记", text: "请在 config.json 的 microservices 中登记 id=k3sctl-adapter，并通过该微服务连接 k3s 控制平面。" });

  return h("div", { className: "k3s-page", "data-testid": "k3sctl-page" },
    h(Panel, {
      title: "k3s Control Plane",
      eyebrow: "Managed by k3sctl-adapter",
      className: "k3s-hero-panel",
      loading: state.loading,
      actions: h(React.Fragment, null,
        h("button", { type: "button", className: "ghost-btn", onClick: load, disabled: state.loading, "data-testid": "k3s-refresh-button" }, state.loading ? "刷新中" : "刷新"),
        onNavigate ? h("button", { type: "button", className: "ghost-btn", onClick: () => onNavigate("apps", "code-queue"), "data-testid": "k3s-open-code-queue" }, "打开 Code Queue") : null,
        h(RawButton, { title: "k3sctl-adapter microservice", data: adapter, onOpen: onRaw, testId: "raw-k3s-adapter" }),
      ),
    },
      h("div", { className: "k3s-hero" },
        h("div", { className: "k3s-orb", "aria-hidden": "true" }, h("span", null, "k3s")),
        h("div", { className: "k3s-hero-copy" },
          h("p", { className: "eyebrow" }, "D601 native control plane"),
          h("h2", null, "UniDesk 只管理 adapter；业务微服务交给 k3s 标准服务路由"),
          h("p", { className: "muted paragraph" }, "Code Queue 的前端/API 请求进入 k3sctl-adapter，再由 adapter 转发到 k3s active service。provider-gateway 只用于维护 adapter 和节点诊断，不再直接管理 Code Queue 容器。"),
          h("div", { className: "k3s-route-strip" },
            h("span", null, "NO FALLBACK"),
            h("code", null, state.data?.runtimePath || "frontend -> backend-core -> k3sctl-adapter"),
          ),
        ),
      ),
      h("div", { className: "metric-grid" },
        h(MetricCard, { label: "控制面", value: state.data?.clusterId || "D601", hint: `adapter ${runtime.providerStatus || "unknown"}`, tone: runtime.providerStatus === "online" ? "ok" : "warn" }),
        h(MetricCard, { label: "代管服务", value: services.length, hint: `${healthyServices}/${services.length || 0} healthy`, tone: healthyServices === services.length && services.length > 0 ? "ok" : "warn" }),
        h(MetricCard, { label: "节点", value: nodes.join(" / ") || "--", hint: "expected k3s nodes" }),
        h(MetricCard, { label: "实例", value: `${healthyInstances}/${totalInstances}`, hint: `active ${primary}`, tone: healthyInstances === totalInstances && totalInstances > 0 ? "ok" : "warn" }),
      ),
      h("div", { className: "k3s-control-plane-grid" },
        h("article", { className: "k3s-control-plane-card" },
          h("span", null, "service proxy"),
          h("strong", null, kubeProxy.configured === true ? "K8S API PROXY" : "PROXY DEGRADED"),
          h("p", null, kubeProxy.configured === true ? `${kubeProxy.mode || "kubernetes-api-service-proxy"} via ${kubeProxy.connectHost || "--"}` : "adapter 必须通过 k8s API service proxy 访问业务服务，不回退到业务容器直连。"),
        ),
        h("article", { className: "k3s-control-plane-card" },
          h("span", null, "manifests"),
          h("strong", null, manifestPaths.length || "--"),
          h("p", null, manifestPaths.join(" / ") || "未配置 manifest"),
        ),
        h("article", { className: "k3s-control-plane-card" },
          h("span", null, "cluster snapshot"),
          h("strong", null, kubectl.enabled === true ? (kubectl.ok === true ? "KUBECTL OK" : "KUBECTL DEGRADED") : "API ONLY"),
          h("p", null, kubectl.enabled === true ? `nodes ${kubectl.nodeCount ?? "--"}` : "控制面页面以 adapter 返回的 k8s service proxy 状态为准；kubectl 只作为可选快照。"),
        ),
      ),
      state.error ? h(UniDeskErrorBanner, { error: state.error }) : null,
      state.refreshedAt ? h("p", { className: "muted paragraph" }, `最近刷新 ${fmtClock(state.refreshedAt)}`) : null,
    ),
    services.length === 0
      ? h(Panel, { title: "代管服务", eyebrow: "k3s services", loading: state.loading }, h(EmptyState, { title: "暂无 k3s 服务", text: "等待 k3sctl-adapter 返回 /api/services；Code Queue 应显示 D601 scheduler/read/write 服务实例。" }))
      : services.map((service) => renderManagedService(service, onRaw)),
  );
}
