import {
  VisuallyHidden
} from "./chunk-54TMLQH3.js";
import {
  useSalesChannelTableColumns,
  useSalesChannelTableEmptyState,
  useSalesChannelTableFilters,
  useSalesChannelTableQuery
} from "./chunk-CKNQJPAG.js";
import "./chunk-MDABSESI.js";
import "./chunk-54RTJBYO.js";
import {
  DataTable
} from "./chunk-OB4NOV4M.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-BDGZ4EQO.js";
import {
  ConditionalTooltip
} from "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import "./chunk-3QSRE5LS.js";
import {
  useApiKey,
  useBatchAddSalesChannelsToApiKey
} from "./chunk-YKDEE7ZL.js";
import {
  useSalesChannels
} from "./chunk-DL2ZIXBO.js";
import "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/api-key-management/api-key-management-sales-channels/api-key-management-sales-channels.tsx
import { useParams } from "react-router-dom";

// src/pages/api-key-management/api-key-management-sales-channels/components/api-key-sales-channels-form/api-key-sales-channels-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  Checkbox,
  Hint,
  createDataTableColumnHelper,
  toast
} from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var AddSalesChannelsToApiKeySchema = zod.object({
  sales_channel_ids: zod.array(zod.string()).min(1)
});
var PAGE_SIZE = 50;
var PREFIX = "sc_add";
var ApiKeySalesChannelsForm = ({
  apiKey,
  preSelected = []
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      sales_channel_ids: []
    },
    resolver: zodResolver(AddSalesChannelsToApiKeySchema)
  });
  const { setValue } = form;
  const [rowSelection, setRowSelection] = useState({});
  const { mutateAsync, isPending: isMutating } = useBatchAddSalesChannelsToApiKey(apiKey);
  const searchParams = useSalesChannelTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const columns = useColumns();
  const filters = useSalesChannelTableFilters();
  const emptyState = useSalesChannelTableEmptyState();
  const { sales_channels, count, isPending } = useSalesChannels(
    { ...searchParams },
    {
      placeholderData: keepPreviousData
    }
  );
  const updater = (selection) => {
    const ids = Object.keys(selection);
    setValue("sales_channel_ids", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(selection);
  };
  const handleSubmit = form.handleSubmit(async (values) => {
    await mutateAsync(values.sales_channel_ids, {
      onSuccess: () => {
        toast.success(
          t("apiKeyManagement.salesChannels.successToast", {
            count: values.sales_channel_ids.length
          })
        );
        handleSuccess();
      },
      onError: (err) => {
        toast.error(err.message);
      }
    });
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "publishable-api-key-sales-channels-form", children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsxs(RouteFocusModal.Header, { "data-testid": "publishable-api-key-sales-channels-form-header", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(VisuallyHidden, { "data-testid": "publishable-api-key-sales-channels-form-title", children: t("apiKeyManagement.salesChannels.title") }) }),
      /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(VisuallyHidden, { "data-testid": "publishable-api-key-sales-channels-form-description", children: t("apiKeyManagement.salesChannels.description") }) }),
      /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end gap-x-2", "data-testid": "publishable-api-key-sales-channels-form-error-container", children: form.formState.errors.sales_channel_ids && /* @__PURE__ */ jsx(Hint, { variant: "error", "data-testid": "publishable-api-key-sales-channels-form-error", children: form.formState.errors.sales_channel_ids.message }) })
    ] }),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-auto", "data-testid": "publishable-api-key-sales-channels-form-body", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        data: sales_channels,
        columns,
        filters,
        getRowId: (row) => row.id,
        rowCount: count,
        layout: "fill",
        emptyState,
        isLoading: isPending,
        rowSelection: {
          state: rowSelection,
          onRowSelectionChange: updater,
          enableRowSelection: (row) => !preSelected.includes(row.id)
        },
        prefix: PREFIX,
        pageSize: PAGE_SIZE,
        autoFocusSearch: true,
        "data-testid": "publishable-api-key-sales-channels-form-table"
      }
    ) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Footer, { "data-testid": "publishable-api-key-sales-channels-form-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", "data-testid": "publishable-api-key-sales-channels-form-cancel-button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isMutating, "data-testid": "publishable-api-key-sales-channels-form-save-button", children: t("actions.save") })
    ] }) })
  ] }) });
};
var columnHelper = createDataTableColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  const base = useSalesChannelTableColumns();
  return useMemo(
    () => [
      columnHelper.select({
        cell: ({ row }) => {
          const isPreSelected = !row.getCanSelect();
          const isSelected = row.getIsSelected() || isPreSelected;
          return /* @__PURE__ */ jsx(
            ConditionalTooltip,
            {
              content: t("apiKeyManagement.salesChannels.alreadyAddedTooltip"),
              showTooltip: isPreSelected,
              children: /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
                Checkbox,
                {
                  checked: isSelected,
                  disabled: isPreSelected,
                  onCheckedChange: (value) => row.toggleSelected(!!value),
                  onClick: (e) => {
                    e.stopPropagation();
                  }
                }
              ) })
            }
          );
        }
      }),
      ...base
    ],
    [t, base]
  );
};

// src/pages/api-key-management/api-key-management-sales-channels/api-key-management-sales-channels.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var ApiKeyManagementAddSalesChannels = () => {
  const { id } = useParams();
  const { api_key, isLoading, isError, error } = useApiKey(id);
  const preSelected = api_key?.sales_channels?.map((sc) => sc.id);
  const ready = !isLoading && api_key;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "publishable-api-key-sales-channels-modal", children: ready && /* @__PURE__ */ jsx2(ApiKeySalesChannelsForm, { apiKey: id, preSelected }) });
};
export {
  ApiKeyManagementAddSalesChannels as Component
};
