import {
  useCustomerGroupTableColumns
} from "./chunk-54EPH67T.js";
import "./chunk-JHIMVLB2.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import "./chunk-ZMC7BKLT.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-634XVU3D.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import {
  useCustomerGroupTableFilters
} from "./chunk-CMHI2RPL.js";
import {
  useCustomerGroupTableQuery
} from "./chunk-VKOE5J66.js";
import "./chunk-HKDFWQ6Q.js";
import "./chunk-SESTTUVM.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 "./chunk-PBQ5M44A.js";
import "./chunk-OH4AABUT.js";
import "./chunk-YKDEE7ZL.js";
import "./chunk-AEMDNTW5.js";
import "./chunk-LYD3C73Z.js";
import "./chunk-7O5NDICV.js";
import "./chunk-46M463BR.js";
import "./chunk-YFRC6GEN.js";
import "./chunk-N6SI4IIT.js";
import "./chunk-JPNPTILP.js";
import "./chunk-DAXXLQKB.js";
import "./chunk-OHOWEMHO.js";
import "./chunk-GKGLVDDV.js";
import "./chunk-WJJXUXSO.js";
import "./chunk-LAPEZATU.js";
import "./chunk-DBNPVU3L.js";
import "./chunk-U7WZYWGA.js";
import "./chunk-ZN7LWXVC.js";
import "./chunk-VYMODH6P.js";
import "./chunk-LEG67A2R.js";
import {
  useBatchCustomerCustomerGroups,
  useCustomerGroups
} from "./chunk-PRBE5CM3.js";
import "./chunk-5TRY5IMZ.js";
import "./chunk-TAKEQAZZ.js";
import "./chunk-B6FG7A6W.js";
import "./chunk-EPHVGD5Z.js";
import "./chunk-ESPLVOFC.js";
import "./chunk-FXWKGNRV.js";
import "./chunk-VDKOJ5WD.js";
import "./chunk-DL2ZIXBO.js";
import "./chunk-Z2QQZOG3.js";
import "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/customers/customers-add-customer-group/customer-add-customer-groups.tsx
import { useParams } from "react-router-dom";

// src/pages/customers/customers-add-customer-group/components/add-customers-form/add-customer-groups-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { ClientError } from "@mercurjs/client";
import { jsx, jsxs } from "react/jsx-runtime";
var AddCustomerGroupsSchema = zod.object({
  customer_group_ids: zod.array(zod.string()).min(1)
});
var PAGE_SIZE = 10;
var AddCustomerGroupsForm = ({
  customerId
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const [isPending, setIsPending] = useState(false);
  const { mutateAsync: batchCustomerCustomerGroups } = useBatchCustomerCustomerGroups(customerId);
  const form = useForm({
    defaultValues: {
      customer_group_ids: []
    },
    resolver: zodResolver(AddCustomerGroupsSchema)
  });
  const { setValue } = form;
  const [rowSelection, setRowSelection] = useState({});
  useEffect(() => {
    setValue(
      "customer_group_ids",
      Object.keys(rowSelection).filter((k) => rowSelection[k]),
      {
        shouldDirty: true,
        shouldTouch: true
      }
    );
  }, [rowSelection, setValue]);
  const { searchParams, raw } = useCustomerGroupTableQuery({
    pageSize: PAGE_SIZE
  });
  const filters = useCustomerGroupTableFilters();
  const {
    customer_groups,
    count,
    isPending: isLoading,
    isError,
    error
  } = useCustomerGroups({
    fields: "*customers",
    ...searchParams
  });
  const updater = (fn) => {
    const state = typeof fn === "function" ? fn(rowSelection) : fn;
    const ids = Object.keys(state);
    setValue("customer_group_ids", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(state);
  };
  const columns = useColumns();
  const { table } = useDataTable({
    data: customer_groups ?? [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: (row) => {
      return !row.original.customers?.map((c) => c.id).includes(customerId);
    },
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  const handleSubmit = form.handleSubmit(async (data) => {
    setIsPending(true);
    try {
      await batchCustomerCustomerGroups({ add: data.customer_group_ids });
      toast.success(
        t("customers.groups.add.success", {
          groups: data.customer_group_ids.map((id) => customer_groups?.find((g) => g.id === id)).filter(Boolean).map((cg) => cg?.name)
        })
      );
      handleSuccess(`/customers/${customerId}`);
    } catch (e) {
      toast.error(e instanceof ClientError ? e.message : "An error occurred");
    } finally {
      setIsPending(false);
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "add-customer-groups-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex h-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      "data-testid": "add-customer-groups-form-keybound",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": "add-customer-groups-form-header", children: /* @__PURE__ */ jsx(
          "div",
          {
            className: "flex items-center justify-end gap-x-2",
            "data-testid": "add-customer-groups-form-header-errors",
            children: form.formState.errors.customer_group_ids && /* @__PURE__ */ jsx(
              Hint,
              {
                variant: "error",
                "data-testid": "add-customer-groups-form-error-hint",
                children: form.formState.errors.customer_group_ids.message
              }
            )
          }
        ) }),
        /* @__PURE__ */ jsx(
          RouteFocusModal.Body,
          {
            className: "size-full overflow-hidden",
            "data-testid": "add-customer-groups-form-body",
            children: /* @__PURE__ */ jsx(
              _DataTable,
              {
                table,
                columns,
                pageSize: PAGE_SIZE,
                count,
                filters,
                orderBy: [
                  { key: "name", label: t("fields.name") },
                  { key: "created_at", label: t("fields.createdAt") },
                  { key: "updated_at", label: t("fields.updatedAt") }
                ],
                isLoading,
                layout: "fill",
                search: "autofocus",
                queryObject: raw,
                noRecords: {
                  message: t("customers.groups.add.list.noRecordsMessage")
                }
              }
            )
          }
        ),
        /* @__PURE__ */ jsxs(RouteFocusModal.Footer, { "data-testid": "add-customer-groups-form-footer", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "secondary",
              size: "small",
              "data-testid": "add-customer-groups-form-cancel-button",
              children: t("actions.cancel")
            }
          ) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "submit",
              variant: "primary",
              size: "small",
              isLoading: isPending,
              "data-testid": "add-customer-groups-form-submit-button",
              children: t("actions.save")
            }
          )
        ] })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  const base = useCustomerGroupTableColumns();
  const columns = useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          const isPreSelected = !row.getCanSelect();
          const isSelected = row.getIsSelected() || isPreSelected;
          const Component = /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              disabled: isPreSelected,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isPreSelected) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("customers.groups.alreadyAddedTooltip"),
                side: "right",
                children: Component
              }
            );
          }
          return Component;
        }
      }),
      ...base
    ],
    [t, base]
  );
  return columns;
};

// src/pages/customers/customers-add-customer-group/customer-add-customer-groups.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var CustomerAddCustomerGroups = () => {
  const { id } = useParams();
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: /* @__PURE__ */ jsx2(AddCustomerGroupsForm, { customerId: id }) });
};
export {
  CustomerAddCustomerGroups as Component
};
