import {
  CUSTOMER_GROUP_DETAIL_FIELDS
} from "./chunk-SPFLYPY6.js";
import {
  useCustomerTableColumns
} from "./chunk-GJM5XI3E.js";
import {
  useCustomerTableQuery
} from "./chunk-GRH7C3QN.js";
import {
  useCustomerTableFilters
} from "./chunk-ZC2ME3UB.js";
import {
  SingleColumnPage
} from "./chunk-YV6MK4PZ.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import {
  SingleColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useCustomerGroup,
  useCustomers,
  useDeleteCustomerGroup,
  useRemoveCustomersFromGroup
} from "./chunk-II3CLUXA.js";

// src/pages/customer-groups/customer-group-detail/customer-group-detail.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";
import { useLinkQuery, WidgetZone } from "@mercurjs/dashboard-shared";

// src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/customer-group-customer-section.tsx
import { XCircle } from "@medusajs/icons";
import {
  Button,
  Checkbox,
  Container,
  Heading,
  toast,
  usePrompt
} from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { DisplayExtensionZone } from "@mercurjs/dashboard-shared";
import { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var CustomerGroupCustomerSection = ({
  group
}) => {
  const [rowSelection, setRowSelection] = useState({});
  const { t } = useTranslation();
  const prompt = usePrompt();
  const { searchParams, raw } = useCustomerTableQuery({ pageSize: PAGE_SIZE });
  const { customers, count, isLoading, isError, error } = useCustomers({
    ...searchParams,
    order: searchParams.order || "email",
    groups: [group.id]
  });
  const columns = useColumns();
  const filters = useCustomerTableFilters(["groups"]);
  const { table } = useDataTable({
    data: customers ?? [],
    columns,
    count,
    getRowId: (row) => row.id,
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    meta: {
      customerGroupId: group.id
    }
  });
  if (isError) {
    throw error;
  }
  const { mutateAsync } = useRemoveCustomersFromGroup(group.id);
  const handleRemove = async () => {
    const keys = Object.keys(rowSelection);
    const res = await prompt({
      title: t("customerGroups.customers.remove.title", {
        count: keys.length
      }),
      description: t("customerGroups.customers.remove.description", {
        count: keys.length
      }),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(keys, {
      onSuccess: () => {
        setRowSelection({});
        toast.success(
          t("customerGroups.customers.remove.successToast", {
            count: keys.length
          })
        );
      },
      onError: (e) => {
        toast.error(e.message);
      }
    });
  };
  return /* @__PURE__ */ jsxs(
    Container,
    {
      className: "divide-y p-0",
      "data-testid": "customer-group-customer-section",
      children: [
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex items-center justify-between px-6 py-4",
            "data-testid": "customer-group-customer-section-header",
            children: [
              /* @__PURE__ */ jsx(
                Heading,
                {
                  level: "h2",
                  "data-testid": "customer-group-customer-section-heading",
                  children: t("customers.domain")
                }
              ),
              /* @__PURE__ */ jsx(
                Link,
                {
                  to: `/customer-groups/${group.id}/add-customers`,
                  "data-testid": "customer-group-customer-section-add-link",
                  children: /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "secondary",
                      size: "small",
                      "data-testid": "customer-group-customer-section-add-button",
                      children: t("general.add")
                    }
                  )
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            columns,
            pageSize: PAGE_SIZE,
            isLoading,
            count,
            navigateTo: (row) => `/customers/${row.id}`,
            filters,
            search: true,
            pagination: true,
            orderBy: [
              { key: "email", label: t("fields.email") },
              { key: "first_name", label: t("fields.firstName") },
              { key: "last_name", label: t("fields.lastName") },
              { key: "has_account", label: t("customers.hasAccount") },
              { key: "created_at", label: t("fields.createdAt") },
              { key: "updated_at", label: t("fields.updatedAt") }
            ],
            defaultOrderBy: "email",
            queryObject: raw,
            commands: [
              {
                action: handleRemove,
                label: t("actions.remove"),
                shortcut: "r"
              }
            ],
            noRecords: {
              title: t("customerGroups.customers.list.noRecordsTitle"),
              message: t("customerGroups.customers.list.noRecordsMessage")
            }
          }
        ),
        /* @__PURE__ */ jsx(
          DisplayExtensionZone,
          {
            model: "customer_group",
            zone: "customers",
            data: group
          }
        )
      ]
    }
  );
};
var CustomerActions = ({
  customer,
  customerGroupId
}) => {
  const { t } = useTranslation();
  const { mutateAsync } = useRemoveCustomersFromGroup(customerGroupId);
  const prompt = usePrompt();
  const handleRemove = async () => {
    const res = await prompt({
      title: t("customerGroups.customers.remove.title", {
        count: 1
      }),
      description: t("customerGroups.customers.remove.description", {
        count: 1
      }),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync([customer.id], {
      onSuccess: () => {
        toast.success(
          t("customerGroups.customers.remove.successToast", { count: 1 })
        );
      },
      onError: (e) => {
        toast.error(e.message);
      }
    });
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(XCircle, {}),
              label: t("actions.remove"),
              onClick: handleRemove
            }
          ]
        }
      ]
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const columns = useCustomerTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...columns,
      columnHelper.display({
        id: "actions",
        cell: ({ row, table }) => {
          const { customerGroupId } = table.options.meta;
          return /* @__PURE__ */ jsx(
            CustomerActions,
            {
              customer: row.original,
              customerGroupId
            }
          );
        }
      })
    ],
    [columns]
  );
};

// src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/customer-group-general-section.tsx
import { PencilSquare, Trash } from "@medusajs/icons";
import { Container as Container2, Heading as Heading2, Text, toast as toast2, usePrompt as usePrompt2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { DisplayExtensionZone as DisplayExtensionZone2, DisplayField } from "@mercurjs/dashboard-shared";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CustomerGroupGeneralSection = ({
  group
}) => {
  const { t } = useTranslation2();
  const prompt = usePrompt2();
  const navigate = useNavigate();
  const { mutateAsync } = useDeleteCustomerGroup(group.id);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("customerGroups.delete.title"),
      description: t("customerGroups.delete.description", {
        name: group.name
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(void 0, {
      onSuccess: () => {
        toast2.success(
          t("customerGroups.delete.successToast", {
            name: group.name
          })
        );
        navigate("/customer-groups", { replace: true });
      },
      onError: (error) => {
        toast2.error(error.message);
      }
    });
  };
  return /* @__PURE__ */ jsxs2(
    Container2,
    {
      className: "divide-y p-0",
      "data-testid": "customer-group-general-section",
      children: [
        /* @__PURE__ */ jsxs2(
          "div",
          {
            className: "flex items-center justify-between px-6 py-4",
            "data-testid": "customer-group-general-section-header",
            children: [
              /* @__PURE__ */ jsx2(DisplayField, { model: "customer_group", zone: "general", id: "name", data: group, children: /* @__PURE__ */ jsx2(Heading2, { "data-testid": "customer-group-general-section-name", children: group.name }) }),
              /* @__PURE__ */ jsx2(
                ActionMenu,
                {
                  groups: [
                    {
                      actions: [
                        {
                          icon: /* @__PURE__ */ jsx2(PencilSquare, {}),
                          label: t("actions.edit"),
                          to: `/customer-groups/${group.id}/edit`
                        }
                      ]
                    },
                    {
                      actions: [
                        {
                          icon: /* @__PURE__ */ jsx2(Trash, {}),
                          label: t("actions.delete"),
                          onClick: handleDelete
                        }
                      ]
                    }
                  ]
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsx2(
          DisplayField,
          {
            model: "customer_group",
            zone: "general",
            id: "customers",
            data: group,
            children: /* @__PURE__ */ jsxs2(
              "div",
              {
                className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4",
                "data-testid": "customer-group-general-section-customers-row",
                children: [
                  /* @__PURE__ */ jsx2(
                    Text,
                    {
                      size: "small",
                      leading: "compact",
                      weight: "plus",
                      "data-testid": "customer-group-general-section-customers-label",
                      children: t("customers.domain")
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    Text,
                    {
                      size: "small",
                      leading: "compact",
                      "data-testid": "customer-group-general-section-customers-value",
                      children: group.customers?.length || "-"
                    }
                  )
                ]
              }
            )
          }
        ),
        /* @__PURE__ */ jsx2(
          DisplayExtensionZone2,
          {
            model: "customer_group",
            zone: "general",
            data: group,
            builtInFieldIds: ["name", "customers"]
          }
        )
      ]
    }
  );
};

// src/pages/customer-groups/customer-group-detail/customer-group-detail.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const query = useLinkQuery("customer_group", CUSTOMER_GROUP_DETAIL_FIELDS);
  const { customer_group, isLoading, isError, error } = useCustomerGroup(
    id,
    query,
    { initialData }
  );
  if (isLoading || !customer_group) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { sections: 2, showJSON: true });
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(SingleColumnPage, { showJSON: true, data: customer_group, hasOutlet: true, children }) : /* @__PURE__ */ jsx3(SingleColumnPage, { showJSON: true, data: customer_group, hasOutlet: true, children: /* @__PURE__ */ jsxs3(WidgetZone, { id: "customer-groups.detail.main", data: customer_group, children: [
    /* @__PURE__ */ jsx3(CustomerGroupGeneralSection, { group: customer_group }),
    /* @__PURE__ */ jsx3(CustomerGroupCustomerSection, { group: customer_group })
  ] }) });
};
var CustomerGroupDetailPage = Object.assign(Root, {
  GeneralSection: CustomerGroupGeneralSection,
  CustomerSection: CustomerGroupCustomerSection
});

export {
  CustomerGroupDetailPage
};
