"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { Tag } from "@open-mercato/ui/primitives/tag";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function ChannelDetailPage() {
  const t = useT();
  const params = useParams();
  const id = params?.id ?? "";
  const [detail, setDetail] = React.useState(null);
  const [health, setHealth] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [errorMessage, setErrorMessage] = React.useState(null);
  const [notFound, setNotFound] = React.useState(false);
  React.useEffect(() => {
    if (!id) return;
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      setErrorMessage(null);
      setNotFound(false);
      const [detailRes, healthRes] = await Promise.all([
        apiCall(`/api/communication_channels/channels/${encodeURIComponent(id)}`),
        apiCall(`/api/communication_channels/channels/${encodeURIComponent(id)}/health`)
      ]).catch((err) => {
        return [
          { ok: false, result: { error: err instanceof Error ? err.message : "load failed" } },
          { ok: false, result: { error: err instanceof Error ? err.message : "load failed" } }
        ];
      });
      if (cancelled) return;
      if (!detailRes.ok) {
        const status = detailRes.status;
        if (status === 404) {
          setNotFound(true);
        } else {
          const body = detailRes.result;
          setErrorMessage(
            body?.error ?? t("communication_channels.errors.loadDetail", "Failed to load channel")
          );
        }
        setDetail(null);
        setHealth(null);
      } else {
        setDetail(detailRes.result ?? null);
        setHealth(healthRes.ok ? healthRes.result ?? null : null);
      }
      setIsLoading(false);
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, [id, t]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("communication_channels.detail.loading", "Loading channel...") }) }) });
  }
  if (notFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("communication_channels.detail.notFound", "Channel not found"),
        backHref: "/backend/communication_channels/channels"
      }
    ) }) });
  }
  if (errorMessage || !detail) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: errorMessage ?? t("communication_channels.errors.loadDetail", "Failed to load channel")
      }
    ) }) });
  }
  const capabilities = detail.capabilities ?? {};
  const capabilityKeys = Object.keys(capabilities);
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    /* @__PURE__ */ jsxs("header", { className: "mb-4 flex flex-wrap items-baseline justify-between gap-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h2", { className: "text-2xl font-semibold", children: detail.displayName }),
        /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
          detail.providerKey,
          " \xB7 ",
          detail.channelType,
          detail.externalIdentifier ? ` \xB7 ${detail.externalIdentifier}` : ""
        ] })
      ] }),
      detail.isActive ? /* @__PURE__ */ jsx(Tag, { variant: "success", dot: true, children: t("communication_channels.status.active", "Active") }) : /* @__PURE__ */ jsx(Tag, { variant: "neutral", children: t("communication_channels.status.inactive", "Inactive") })
    ] }),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "mb-4 rounded-md border bg-card p-4",
        "aria-label": t("communication_channels.detail.capabilities", "Capabilities"),
        children: [
          /* @__PURE__ */ jsx("header", { className: "mb-2 text-overline text-muted-foreground", children: t("communication_channels.detail.capabilities", "Capabilities") }),
          capabilityKeys.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
            "communication_channels.detail.noCapabilities",
            "No capabilities snapshot recorded for this channel yet."
          ) }) : /* @__PURE__ */ jsx("dl", { className: "grid grid-cols-2 gap-x-6 gap-y-1 text-sm md:grid-cols-3", children: capabilityKeys.sort((a, b) => a.localeCompare(b)).map((key) => /* @__PURE__ */ jsxs(React.Fragment, { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: key }),
            /* @__PURE__ */ jsx("dd", { className: "md:col-span-2", children: renderCapabilityValue(capabilities[key]) })
          ] }, key)) })
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-md border bg-card p-4",
        "aria-label": t("communication_channels.detail.health", "Delivery health (last 24h)"),
        children: [
          /* @__PURE__ */ jsxs("header", { className: "mb-2 flex items-baseline justify-between text-overline text-muted-foreground", children: [
            /* @__PURE__ */ jsx("span", { children: t("communication_channels.detail.health", "Delivery health (last 24h)") }),
            health ? /* @__PURE__ */ jsxs("span", { className: "text-xs", children: [
              health.totalsLast24h,
              " ",
              t("communication_channels.detail.messages", "messages")
            ] }) : null
          ] }),
          health ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("ul", { className: "mb-3 flex flex-wrap gap-2 text-xs", children: Object.entries(health.counts).map(([status, count]) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(Tag, { variant: tagVariantForStatus(status), children: [
              status,
              ": ",
              count
            ] }) }, status)) }),
            health.recentFailures.length > 0 ? /* @__PURE__ */ jsxs("details", { children: [
              /* @__PURE__ */ jsxs("summary", { className: "cursor-pointer text-sm text-muted-foreground", children: [
                t("communication_channels.detail.recentFailures", "Recent failures"),
                " (",
                health.recentFailures.length,
                ")"
              ] }),
              /* @__PURE__ */ jsx("ul", { className: "mt-2 space-y-1 text-xs", children: health.recentFailures.map((failure) => /* @__PURE__ */ jsxs("li", { className: "rounded border bg-muted p-2", children: [
                /* @__PURE__ */ jsxs("div", { className: "font-mono text-xs text-muted-foreground", children: [
                  failure.messageId,
                  " \xB7 ",
                  failure.direction,
                  " \xB7",
                  " ",
                  failure.createdAt ?? "\u2014"
                ] }),
                failure.lastError ? /* @__PURE__ */ jsx("div", { className: "mt-1", children: failure.lastError }) : null
              ] }, failure.id)) })
            ] }) : null
          ] }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("communication_channels.detail.noHealth", "No health data available.") })
        ]
      }
    )
  ] }) });
}
function renderCapabilityValue(value) {
  if (value === null || value === void 0) return "\u2014";
  if (Array.isArray(value)) return value.join(", ");
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}
function tagVariantForStatus(status) {
  switch (status) {
    case "sent":
    case "delivered":
    case "read":
      return "success";
    case "failed":
      return "error";
    case "pending":
    case "queued":
      return "warning";
    default:
      return "neutral";
  }
}
export {
  ChannelDetailPage as default
};
//# sourceMappingURL=page.js.map
