import {
  useCustomerGroupTableQuery
} from "./chunk-VKOE5J66.js";
import {
  TextCell,
  TextHeader
} from "./chunk-JHIMVLB2.js";
import {
  useCustomerGroupTableFilters
} from "./chunk-CMHI2RPL.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import "./chunk-W34KDYZA.js";
import {
  useBatchCustomerCustomerGroups,
  useCustomerGroups
} from "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

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

// src/pages/customers/[id]/add-customer-groups/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 { 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: "id,name,customers.id",
    ...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?.some((c) => c.id === 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,
        remove: []
      });
      const names = data.customer_group_ids.map((id) => customer_groups?.find((g) => g.id === id)?.name).filter(Boolean);
      toast.success(
        names.length === 1 ? t("customers.groups.add.successOne", { groups: names[0] }) : t("customers.groups.add.successMany", {
          groups: names.join(", ")
        })
      );
      handleSuccess(`/customers/${customerId}`);
    } catch (e) {
      toast.error(e.message);
    } finally {
      setIsPending(false);
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex h-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { children: /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end gap-x-2", children: form.formState.errors.customer_group_ids && /* @__PURE__ */ jsx(Hint, { variant: "error", children: form.formState.errors.customer_group_ids.message }) }) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "size-full overflow-hidden", 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, { children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "submit",
              variant: "primary",
              size: "small",
              isLoading: isPending,
              children: t("actions.save")
            }
          )
        ] })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  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 Component2 = /* @__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: Component2
              }
            );
          }
          return Component2;
        }
      }),
      columnHelper.accessor("name", {
        header: () => /* @__PURE__ */ jsx(TextHeader, { text: t("fields.name") }),
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(TextCell, { text: row.original?.name || "-" });
        }
      })
    ],
    [t]
  );
  return columns;
};

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