import {
  useCustomerTableColumns
} from "./chunk-QG6PLWNH.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import {
  SingleColumnPage
} from "./chunk-H6MYB7GB.js";
import {
  SingleColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useCustomerTableFilters
} from "./chunk-I5THQVYP.js";
import {
  useCustomerTableQuery
} from "./chunk-PVZBDWLK.js";
import {
  useCustomerGroup,
  useCustomers,
  useDeleteCustomerGroup,
  useRemoveCustomersFromGroup
} from "./chunk-PRBE5CM3.js";

// src/pages/customer-groups/customer-group-detail/customer-group-detail.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";

// src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/customer-group-customer-section.tsx
import { PencilSquare, Trash } from "@medusajs/icons";
import { Button, Checkbox, Container, Heading, 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 { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 10;
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,
    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({});
      }
    });
  };
  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") }
        ],
        queryObject: raw,
        commands: [
          {
            action: handleRemove,
            label: t("actions.remove"),
            shortcut: "r"
          }
        ],
        noRecords: {
          message: t("customerGroups.customers.list.noRecordsMessage")
        }
      }
    )
  ] });
};
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]);
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      "data-testid": `customer-group-customer-section-row-actions-${customer.id}`,
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(PencilSquare, {}),
              label: t("actions.edit"),
              to: `/customers/${customer.id}/edit`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(Trash, {}),
              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 as PencilSquare2, Trash as Trash2 } from "@medusajs/icons";
import { Container as Container2, Heading as Heading2, Text, toast, usePrompt as usePrompt2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useNavigate } from "react-router-dom";
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: () => {
        toast.success(
          t("customerGroups.delete.successToast", {
            name: group.name
          })
        );
        navigate("/customer-groups", { replace: true });
      },
      onError: (error) => {
        toast.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(Heading2, { "data-testid": "customer-group-general-section-name", children: group.name }),
      /* @__PURE__ */ jsx2(
        ActionMenu,
        {
          "data-testid": "customer-group-general-section-action-menu",
          groups: [
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx2(PencilSquare2, {}),
                  label: t("actions.edit"),
                  to: `/customer-groups/${group.id}/edit`
                }
              ]
            },
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx2(Trash2, {}),
                  label: t("actions.delete"),
                  onClick: handleDelete
                }
              ]
            }
          ]
        }
      )
    ] }),
    /* @__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 || "-" })
    ] })
  ] });
};

// src/pages/customer-groups/customer-group-detail/constants.ts
var CUSTOMER_GROUP_DETAIL_FIELDS = "+customers.id";

// 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 { customer_group, isLoading, isError, error } = useCustomerGroup(
    id,
    {
      fields: CUSTOMER_GROUP_DETAIL_FIELDS
    },
    { initialData }
  );
  if (isLoading || !customer_group) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { sections: 2, showJSON: true, showMetadata: true });
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(SingleColumnPage, { showJSON: true, showMetadata: true, data: customer_group, children }) : /* @__PURE__ */ jsxs3(SingleColumnPage, { showJSON: true, showMetadata: true, 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 {
  CUSTOMER_GROUP_DETAIL_FIELDS,
  CustomerGroupDetailPage
};
