import {
  useProductTableColumns
} from "./chunk-Z5I2Z6L3.js";
import "./chunk-FWPGOIFA.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-WIYFXWRI.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import "./chunk-YBZWO4ZV.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-3EF54XFY.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-Y7QKP6QU.js";
import {
  useProductTableFilters
} from "./chunk-WSR2ZXAJ.js";
import {
  useProductTableQuery
} from "./chunk-VVWB3GIK.js";
import "./chunk-KBYZLKI4.js";
import "./chunk-YWWUOGJA.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import "./chunk-O4STPJR2.js";
import "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import {
  useSalesChannel,
  useSalesChannelAddProducts
} from "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import {
  useProducts
} from "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/sales-channels/sales-channel-add-products/sales-channel-add-products.tsx
import { useParams } from "react-router-dom";

// src/pages/sales-channels/sales-channel-add-products/components/add-products-to-sales-channel-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper
} from "@tanstack/react-table";
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 AddProductsToSalesChannelSchema = zod.object({
  product_ids: zod.array(zod.string()).min(1)
});
var PAGE_SIZE = 50;
var AddProductsToSalesChannelForm = ({
  salesChannel
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      product_ids: []
    },
    resolver: zodResolver(AddProductsToSalesChannelSchema)
  });
  const { setValue } = form;
  const { mutateAsync, isPending } = useSalesChannelAddProducts(salesChannel.id);
  const [rowSelection, setRowSelection] = useState({});
  const updater = (fn) => {
    const state = typeof fn === "function" ? fn(rowSelection) : fn;
    const ids = Object.keys(state);
    setValue("product_ids", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(state);
  };
  const { searchParams, raw } = useProductTableQuery({ pageSize: PAGE_SIZE });
  const {
    products,
    count,
    isPending: isLoading,
    isError,
    error
  } = useProducts(
    {
      fields: "*variants,*sales_channels",
      ...searchParams
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const columns = useColumns();
  const filters = useProductTableFilters(["sales_channel_id"]);
  const { table } = useDataTable({
    data: products ?? [],
    columns,
    enableRowSelection: (row) => {
      return !row.original.sales_channels?.map((sc) => sc.id).includes(salesChannel.id);
    },
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    count,
    rowSelection: {
      state: rowSelection,
      updater
    },
    meta: {
      salesChannelId: salesChannel.id
    }
  });
  const handleSubmit = form.handleSubmit(async (values) => {
    await mutateAsync(values.product_ids, {
      onSuccess: () => {
        toast.success(t("salesChannels.toast.update"));
        handleSuccess();
      },
      onError: (error2) => toast.error(error2.message)
    });
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "sales-channel-add-products-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": "sales-channel-add-products-form-header", children: /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end gap-x-2", children: form.formState.errors.product_ids && /* @__PURE__ */ jsx(Hint, { variant: "error", "data-testid": "sales-channel-add-products-form-error", children: form.formState.errors.product_ids.message }) }) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex size-full flex-col overflow-y-auto", "data-testid": "sales-channel-add-products-form-body", children: /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            count,
            columns,
            pageSize: PAGE_SIZE,
            isLoading,
            filters,
            orderBy: [
              { key: "title", label: t("fields.title") },
              { key: "status", label: t("fields.status") },
              { key: "created_at", label: t("fields.createdAt") },
              { key: "updated_at", label: t("fields.updatedAt") }
            ],
            queryObject: raw,
            layout: "fill",
            pagination: true,
            search: "autofocus",
            noRecords: {
              message: t("salesChannels.products.add.list.noRecordsMessage")
            },
            "data-testid": "sales-channel-add-products-form-table"
          }
        ) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { "data-testid": "sales-channel-add-products-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": "sales-channel-add-products-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, "data-testid": "sales-channel-add-products-form-save-button", children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useProductTableColumns();
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value),
              "data-testid": "sales-channel-add-products-form-select-all-checkbox"
            }
          );
        },
        cell: ({ row, table }) => {
          const { salesChannelId } = table.options.meta;
          const isAdded = row.original.sales_channels?.map((sc) => sc.id).includes(salesChannelId);
          const isSelected = row.getIsSelected() || isAdded;
          const Component = /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              disabled: isAdded,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `sales-channel-add-products-form-select-checkbox-${row.original.id}`
            }
          );
          if (isAdded) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("salesChannels.productAlreadyAdded"),
                side: "right",
                children: Component
              }
            );
          }
          return Component;
        }
      }),
      ...base
    ],
    [t, base]
  );
};

// src/pages/sales-channels/sales-channel-add-products/sales-channel-add-products.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var SalesChannelAddProducts = () => {
  const { id } = useParams();
  const {
    sales_channel,
    isPending: isLoading,
    isError,
    error
  } = useSalesChannel(id);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "sales-channel-add-products-modal", children: !isLoading && sales_channel && /* @__PURE__ */ jsx2(AddProductsToSalesChannelForm, { salesChannel: sales_channel }) });
};
export {
  SalesChannelAddProducts as Component
};
