import {
  getApiKeyStatusProps,
  getApiKeyTypeProps,
  prettifyRedactedToken
} from "./chunk-XFR5JLNF.js";
import {
  UserLink
} from "./chunk-C4JUURO5.js";
import {
  SingleColumnPage
} from "./chunk-H6MYB7GB.js";
import {
  useSalesChannelTableColumns,
  useSalesChannelTableEmptyState,
  useSalesChannelTableFilters,
  useSalesChannelTableQuery
} from "./chunk-CKNQJPAG.js";
import {
  DataTable
} from "./chunk-OB4NOV4M.js";
import {
  SingleColumnPageSkeleton,
  Skeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useDate
} from "./chunk-UZWFZMOX.js";
import {
  useApiKey,
  useBatchRemoveSalesChannelsFromApiKey,
  useDeleteApiKey,
  useRevokeApiKey
} from "./chunk-YKDEE7ZL.js";
import {
  useUser
} from "./chunk-GKGLVDDV.js";
import {
  useSalesChannels
} from "./chunk-DL2ZIXBO.js";

// src/pages/api-key-management/api-key-management-detail/api-key-management-detail.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";

// src/pages/api-key-management/api-key-management-detail/components/api-key-general-section/api-key-general-section.tsx
import { PencilSquare, Trash, XCircle } from "@medusajs/icons";
import {
  Badge,
  Container,
  Copy,
  Heading,
  StatusBadge,
  Text,
  toast,
  usePrompt
} from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var ApiKeyGeneralSection = ({ apiKey }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const prompt = usePrompt();
  const { getFullDate } = useDate();
  const { mutateAsync: revokeAsync } = useRevokeApiKey(apiKey.id);
  const { mutateAsync: deleteAsync } = useDeleteApiKey(apiKey.id);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("apiKeyManagement.delete.warning", {
        title: apiKey.title
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await deleteAsync(void 0, {
      onSuccess: () => {
        toast.success(
          t("apiKeyManagement.delete.successToast", {
            title: apiKey.title
          })
        );
        navigate("..", { replace: true });
      },
      onError: (err) => {
        toast.error(err.message);
      }
    });
  };
  const handleRevoke = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("apiKeyManagement.revoke.warning", {
        title: apiKey.title
      }),
      confirmText: t("apiKeyManagement.actions.revoke"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await revokeAsync(void 0, {
      onSuccess: () => {
        toast.success(
          t("apiKeyManagement.revoke.successToast", {
            title: apiKey.title
          })
        );
      },
      onError: (err) => {
        toast.error(err.message);
      }
    });
  };
  const dangerousActions = [
    {
      icon: /* @__PURE__ */ jsx(Trash, {}),
      label: t("actions.delete"),
      onClick: handleDelete,
      disabled: !apiKey.revoked_at
    }
  ];
  if (!apiKey.revoked_at) {
    dangerousActions.unshift({
      icon: /* @__PURE__ */ jsx(XCircle, {}),
      label: t("apiKeyManagement.actions.revoke"),
      onClick: handleRevoke,
      disabled: !!apiKey.revoked_at
    });
  }
  const apiKeyStatus = getApiKeyStatusProps(apiKey.revoked_at, t);
  const apiKeyType = getApiKeyTypeProps(apiKey.type, t);
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", "data-testid": `${apiKey.type}-api-key-general-section`, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-header`, children: [
      /* @__PURE__ */ jsx(Heading, { "data-testid": `${apiKey.type}-api-key-general-section-heading`, children: apiKey.title }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-4", "data-testid": `${apiKey.type}-api-key-general-section-actions`, children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-x-2", "data-testid": `${apiKey.type}-api-key-general-section-status`, children: /* @__PURE__ */ jsx(StatusBadge, { color: apiKeyStatus.color, "data-testid": `${apiKey.type}-api-key-general-section-status-badge`, children: apiKeyStatus.label }) }),
        /* @__PURE__ */ jsx(
          ActionMenu,
          {
            groups: [
              {
                actions: [
                  {
                    label: t("actions.edit"),
                    icon: /* @__PURE__ */ jsx(PencilSquare, {}),
                    to: "edit"
                  }
                ]
              },
              {
                actions: dangerousActions
              }
            ],
            "data-testid": `${apiKey.type}-api-key-general-section-action-menu`
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-key-row`, children: [
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-key-label`, children: t("fields.key") }),
      apiKey.type === "secret" ? /* @__PURE__ */ jsx(Badge, { size: "2xsmall", className: "inline-block w-fit", "data-testid": `${apiKey.type}-api-key-general-section-key-badge`, children: prettifyRedactedToken(apiKey.redacted) }) : /* @__PURE__ */ jsx(Copy, { asChild: true, content: apiKey.token, className: "cursor-pointer", "data-testid": `${apiKey.type}-api-key-general-section-key-copy`, children: /* @__PURE__ */ jsx(Badge, { size: "2xsmall", className: "text-ui-tag-neutral-text", "data-testid": `${apiKey.type}-api-key-general-section-key-badge`, children: prettifyRedactedToken(apiKey.redacted) }) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-type-row`, children: [
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-type-label`, children: t("fields.type") }),
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", "data-testid": `${apiKey.type}-api-key-general-section-type-value`, children: apiKeyType.label })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-last-used-row`, children: [
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-last-used-label`, children: t("apiKeyManagement.fields.lastUsedAtLabel") }),
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", "data-testid": `${apiKey.type}-api-key-general-section-last-used-value`, children: apiKey.last_used_at ? getFullDate({ date: apiKey.last_used_at, includeTime: true }) : "-" })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-created-by-row`, children: [
      /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-created-by-label`, children: t("apiKeyManagement.fields.createdByLabel") }),
      /* @__PURE__ */ jsx(ActionBy, { userId: apiKey.created_by, "data-testid": `${apiKey.type}-api-key-general-section-created-by-value` })
    ] }),
    apiKey.revoked_at && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-revoked-at-row`, children: [
        /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-revoked-at-label`, children: t("apiKeyManagement.fields.revokedAtLabel") }),
        /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", "data-testid": `${apiKey.type}-api-key-general-section-revoked-at-value`, children: getFullDate({ date: apiKey.revoked_at, includeTime: true }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": `${apiKey.type}-api-key-general-section-revoked-by-row`, children: [
        /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `${apiKey.type}-api-key-general-section-revoked-by-label`, children: t("apiKeyManagement.fields.revokedByLabel") }),
        /* @__PURE__ */ jsx(ActionBy, { userId: apiKey.revoked_by, "data-testid": `${apiKey.type}-api-key-general-section-revoked-by-value` })
      ] })
    ] })
  ] });
};
var ActionBy = ({ userId, "data-testid": dataTestId }) => {
  const { user, isLoading, isError, error } = useUser(userId, void 0, {
    enabled: !!userId
  });
  if (!userId) {
    return /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", "data-testid": dataTestId, children: "-" });
  }
  if (isError) {
    throw error;
  }
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[20px_1fr]", "data-testid": dataTestId, children: [
      /* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-5 rounded-full" }),
      /* @__PURE__ */ jsx(Skeleton, { className: "w-full max-w-[220px]" })
    ] });
  }
  if (!user) {
    return /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", "data-testid": dataTestId, children: "-" });
  }
  return /* @__PURE__ */ jsx(UserLink, { ...user, "data-testid": dataTestId });
};

// src/pages/api-key-management/api-key-management-detail/components/api-key-sales-channel-section/api-key-sales-channel-section.tsx
import { PencilSquare as PencilSquare2, Trash as Trash2 } from "@medusajs/icons";
import {
  Container as Container2,
  createDataTableColumnHelper,
  createDataTableCommandHelper,
  toast as toast2,
  usePrompt as usePrompt2
} from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { useCallback, useMemo, useState } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useNavigate as useNavigate2 } from "react-router-dom";
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var PREFIX = "sc";
var ApiKeySalesChannelSection = ({
  apiKey
}) => {
  const [rowSelection, setRowSelection] = useState({});
  const { t } = useTranslation2();
  const searchParams = useSalesChannelTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { sales_channels, count, isPending } = useSalesChannels(
    { ...searchParams, publishable_key_id: apiKey.id },
    {
      placeholderData: keepPreviousData
    }
  );
  const columns = useColumns(apiKey.id);
  const filters = useSalesChannelTableFilters();
  const commands = useCommands(apiKey.id, setRowSelection);
  const emptyState = useSalesChannelTableEmptyState();
  return /* @__PURE__ */ jsx2(Container2, { className: "divide-y p-0", "data-testid": `publishable-api-key-sales-channels-section`, children: /* @__PURE__ */ jsx2(
    DataTable,
    {
      data: sales_channels,
      columns,
      filters,
      commands,
      heading: t("salesChannels.domain"),
      getRowId: (row) => row.id,
      rowCount: count,
      isLoading: isPending,
      emptyState,
      rowSelection: {
        state: rowSelection,
        onRowSelectionChange: setRowSelection
      },
      rowHref: (row) => `/settings/sales-channels/${row.id}`,
      action: {
        label: t("actions.add"),
        to: "sales-channels"
      },
      prefix: PREFIX,
      pageSize: PAGE_SIZE,
      "data-testid": "publishable-api-key-sales-channels-table"
    }
  ) });
};
var columnHelper = createDataTableColumnHelper();
var useColumns = (id) => {
  const { t } = useTranslation2();
  const navigate = useNavigate2();
  const prompt = usePrompt2();
  const base = useSalesChannelTableColumns();
  const { mutateAsync } = useBatchRemoveSalesChannelsFromApiKey(id);
  const handleDelete = useCallback(
    async (salesChannel) => {
      const res = await prompt({
        title: t("general.areYouSure"),
        description: t("apiKeyManagement.removeSalesChannel.warning", {
          name: salesChannel.name
        }),
        confirmText: t("actions.delete"),
        cancelText: t("actions.cancel")
      });
      if (!res) {
        return;
      }
      await mutateAsync([salesChannel.id], {
        onSuccess: () => {
          toast2.success(
            t("apiKeyManagement.removeSalesChannel.successToast", {
              count: 1
            })
          );
        },
        onError: (err) => {
          toast2.error(err.message);
        }
      });
    },
    [mutateAsync, prompt, t]
  );
  return useMemo(
    () => [
      columnHelper.select(),
      ...base,
      columnHelper.action({
        actions: (ctx) => [
          [
            {
              label: t("actions.edit"),
              icon: /* @__PURE__ */ jsx2(PencilSquare2, {}),
              onClick: () => {
                navigate(`/settings/sales-channels/${ctx.row.original.id}/edit`);
              }
            }
          ],
          [
            {
              icon: /* @__PURE__ */ jsx2(Trash2, {}),
              label: t("actions.delete"),
              onClick: () => handleDelete(ctx.row.original)
            }
          ]
        ]
      })
    ],
    [base, handleDelete, navigate, t]
  );
};
var commandHelper = createDataTableCommandHelper();
var useCommands = (id, setRowSelection) => {
  const { t } = useTranslation2();
  const prompt = usePrompt2();
  const { mutateAsync } = useBatchRemoveSalesChannelsFromApiKey(id);
  const handleRemove = useCallback(
    async (rowSelection) => {
      const keys = Object.keys(rowSelection);
      const res = await prompt({
        title: t("general.areYouSure"),
        description: t("apiKeyManagement.removeSalesChannel.warningBatch", {
          count: keys.length
        }),
        confirmText: t("actions.continue"),
        cancelText: t("actions.cancel")
      });
      if (!res) {
        return;
      }
      await mutateAsync(keys, {
        onSuccess: () => {
          toast2.success(
            t("apiKeyManagement.removeSalesChannel.successToastBatch", {
              count: keys.length
            })
          );
          setRowSelection({});
        },
        onError: (err) => {
          toast2.error(err.message);
        }
      });
    },
    [mutateAsync, prompt, t, setRowSelection]
  );
  return useMemo(
    () => [
      commandHelper.command({
        action: handleRemove,
        label: t("actions.remove"),
        shortcut: "r"
      })
    ],
    [handleRemove, t]
  );
};

// src/pages/api-key-management/api-key-management-detail/api-key-management-detail.tsx
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const { api_key, isLoading, isError, error } = useApiKey(id, void 0, {
    initialData
  });
  if (isLoading || !api_key) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { showJSON: true, sections: 1 });
  }
  if (isError) {
    throw error;
  }
  const isPublishable = api_key.type === "publishable" /* PUBLISHABLE */;
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(
    SingleColumnPage,
    {
      hasOutlet: true,
      showJSON: true,
      data: api_key,
      "data-testid": `${api_key.type}-api-key-detail-page`,
      children
    }
  ) : /* @__PURE__ */ jsxs2(
    SingleColumnPage,
    {
      hasOutlet: true,
      showJSON: true,
      data: api_key,
      "data-testid": `${api_key.type}-api-key-detail-page`,
      children: [
        /* @__PURE__ */ jsx3(ApiKeyGeneralSection, { apiKey: api_key }),
        isPublishable && /* @__PURE__ */ jsx3(ApiKeySalesChannelSection, { apiKey: api_key })
      ]
    }
  );
};
var ApiKeyManagementDetailPage = Object.assign(Root, {
  GeneralSection: ApiKeyGeneralSection,
  SalesChannelSection: ApiKeySalesChannelSection
});

export {
  ApiKeyManagementDetailPage
};
