import {
  ListSummary
} from "./chunk-4F5GP7J7.js";
import {
  useDeletePriceListAction
} from "./chunk-JCSPXBS3.js";
import {
  getPriceListStatus
} from "./chunk-U5MJIHLY.js";
import {
  DateRangeDisplay
} from "./chunk-RK5N3XIX.js";
import {
  useProductTableColumns
} from "./chunk-Z5I2Z6L3.js";
import {
  TwoColumnPage
} from "./chunk-E74OUNA3.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import {
  Skeleton,
  TwoColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useProductTableFilters
} from "./chunk-LNAXUDW2.js";
import {
  useProductTableQuery
} from "./chunk-VVWB3GIK.js";
import {
  usePriceList,
  usePriceListLinkProducts
} from "./chunk-DBNPVU3L.js";
import {
  useCustomerGroups
} from "./chunk-PRBE5CM3.js";
import {
  useProducts
} from "./chunk-5CK6XEFV.js";

// src/pages/price-lists/price-list-detail/price-list-detail.tsx
import { Children } from "react";
import { useParams } from "react-router-dom";

// src/pages/price-lists/price-list-detail/components/price-list-configuration-section/price-list-configuration-section.tsx
import { PencilSquare } from "@medusajs/icons";
import { Container, Heading } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var PriceListConfigurationSection = ({
  priceList
}) => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4", "data-testid": "price-list-configuration-section-container", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", "data-testid": "price-list-configuration-section-header", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Heading, { level: "h2", "data-testid": "price-list-configuration-section-heading", children: t("priceLists.configuration.header") }),
        /* @__PURE__ */ jsx(CustomerGroupDisplay, { priceList })
      ] }),
      /* @__PURE__ */ jsx(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("actions.edit"),
                  to: "configuration",
                  icon: /* @__PURE__ */ jsx(PencilSquare, {})
                }
              ]
            }
          ],
          "data-testid": "price-list-configuration-section-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      DateRangeDisplay,
      {
        endsAt: priceList.ends_at,
        startsAt: priceList.starts_at,
        showTime: true,
        "data-testid": "price-list-configuration-section-date-range"
      }
    )
  ] });
};
var CustomerGroupDisplay = ({
  priceList
}) => {
  const { t } = useTranslation();
  const customerGroupIds = priceList.rules["customer.groups.id"];
  const { customer_groups, isPending, isError } = useCustomerGroups(
    {
      id: customerGroupIds
    },
    {
      enabled: !!customerGroupIds?.length
    }
  );
  if (isError || !customerGroupIds?.length) {
    return null;
  }
  if (isPending || !customer_groups) {
    return /* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-full max-w-48" });
  }
  return /* @__PURE__ */ jsxs("div", { className: "txt-small-plus text-ui-fg-muted flex items-center gap-x-1.5", children: [
    /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle", children: t("priceLists.fields.customerAvailability.attribute") }),
    /* @__PURE__ */ jsx("span", { children: "\xB7" }),
    /* @__PURE__ */ jsx(
      ListSummary,
      {
        list: customer_groups.map((group) => group.name),
        n: 1,
        className: "txt-small-plus text-ui-fg-muted"
      }
    )
  ] });
};

// src/pages/price-lists/price-list-detail/components/price-list-general-section/price-list-general-section.tsx
import { PencilSquare as PencilSquare2, Trash } from "@medusajs/icons";
import { Container as Container2, Heading as Heading2, StatusBadge, Text } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var PriceListGeneralSection = ({
  priceList
}) => {
  const { t } = useTranslation2();
  const overrideCount = priceList.prices?.length || 0;
  const { color, text } = getPriceListStatus(t, priceList);
  const handleDelete = useDeletePriceListAction({ priceList });
  const type = priceList.type === "sale" ? t("priceLists.fields.type.options.sale.label") : t("priceLists.fields.type.options.override.label");
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", "data-testid": "price-list-general-section-container", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "price-list-general-section-header", children: [
      /* @__PURE__ */ jsx2(Heading2, { "data-testid": "price-list-general-section-title", children: priceList.title }),
      /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-4", children: [
        /* @__PURE__ */ jsx2(StatusBadge, { color, "data-testid": "price-list-general-section-status", children: text }),
        /* @__PURE__ */ jsx2(
          ActionMenu,
          {
            groups: [
              {
                actions: [
                  {
                    label: t("actions.edit"),
                    to: "edit",
                    icon: /* @__PURE__ */ jsx2(PencilSquare2, {})
                  }
                ]
              },
              {
                actions: [
                  {
                    label: t("actions.delete"),
                    onClick: handleDelete,
                    icon: /* @__PURE__ */ jsx2(Trash, {})
                  }
                ]
              }
            ],
            "data-testid": "price-list-general-section-action-menu"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "price-list-general-section-type", children: [
      /* @__PURE__ */ jsx2(Text, { leading: "compact", size: "small", weight: "plus", "data-testid": "price-list-general-section-type-label", children: t("fields.type") }),
      /* @__PURE__ */ jsx2(Text, { size: "small", className: "text-pretty", "data-testid": "price-list-general-section-type-value", children: type })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "price-list-general-section-description", children: [
      /* @__PURE__ */ jsx2(Text, { leading: "compact", size: "small", weight: "plus", "data-testid": "price-list-general-section-description-label", children: t("fields.description") }),
      /* @__PURE__ */ jsx2(Text, { size: "small", className: "text-pretty", "data-testid": "price-list-general-section-description-value", children: priceList.description })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "price-list-general-section-price-overrides", children: [
      /* @__PURE__ */ jsx2(Text, { leading: "compact", size: "small", weight: "plus", "data-testid": "price-list-general-section-price-overrides-label", children: t("priceLists.fields.priceOverrides.label") }),
      /* @__PURE__ */ jsx2(Text, { size: "small", className: "text-pretty", "data-testid": "price-list-general-section-price-overrides-value", children: overrideCount || "-" })
    ] })
  ] });
};

// src/pages/price-lists/price-list-detail/components/price-list-product-section/price-list-product-section.tsx
import { ExclamationCircle, PencilSquare as PencilSquare3, Plus, Trash as Trash2 } from "@medusajs/icons";
import { Checkbox, Container as Container3, Heading as Heading3, Text as Text2, toast, usePrompt } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation as useTranslation3 } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var PREFIX = "p";
var PriceListProductSection = ({
  priceList
}) => {
  const { t } = useTranslation3();
  const navigate = useNavigate();
  const prompt = usePrompt();
  const [rowSelection, setRowSelection] = useState({});
  const { searchParams, raw } = useProductTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { products, count, isLoading, isError, error } = useProducts(
    {
      ...searchParams,
      price_list_id: [priceList.id]
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const filters = useProductTableFilters();
  const columns = useColumns(priceList);
  const { mutateAsync } = usePriceListLinkProducts(priceList.id);
  const { table } = useDataTable({
    data: products || [],
    count,
    columns,
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    prefix: PREFIX
  });
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("priceLists.products.delete.confirmation", {
        count: Object.keys(rowSelection).length
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    mutateAsync(
      {
        remove: Object.keys(rowSelection)
      },
      {
        onSuccess: () => {
          toast.success(
            t("priceLists.products.delete.successToast", {
              count: Object.keys(rowSelection).length
            })
          );
          setRowSelection({});
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  const handleEdit = async () => {
    const ids = Object.keys(rowSelection).join(",");
    navigate(`products/edit?ids[]=${ids}`);
  };
  return /* @__PURE__ */ jsxs3(Container3, { className: "divide-y p-0", "data-testid": "price-list-product-section-container", children: [
    /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "price-list-product-section-header", children: [
      /* @__PURE__ */ jsx3(Heading3, { "data-testid": "price-list-product-section-heading", children: t("priceLists.products.header") }),
      /* @__PURE__ */ jsx3(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("priceLists.products.actions.addProducts"),
                  to: "products/add",
                  icon: /* @__PURE__ */ jsx3(Plus, {})
                },
                {
                  label: t("priceLists.products.actions.editPrices"),
                  to: "products/edit",
                  icon: /* @__PURE__ */ jsx3(PencilSquare3, {}),
                  disabled: count === 0,
                  disabledTooltip: t("priceLists.products.actions.editPricesDisabled")
                }
              ]
            }
          ],
          "data-testid": "price-list-product-section-action-menu"
        }
      )
    ] }),
    isError ? /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-x-2 px-6 py-4", "data-testid": "price-list-product-section-error", children: [
      /* @__PURE__ */ jsx3(ExclamationCircle, { className: "text-ui-fg-subtle" }),
      /* @__PURE__ */ jsx3(Text2, { size: "small", className: "text-ui-fg-subtle", children: error?.message || t("general.error") })
    ] }) : /* @__PURE__ */ jsx3(
      _DataTable,
      {
        table,
        filters,
        columns,
        count,
        pageSize: PAGE_SIZE,
        isLoading,
        navigateTo: (row) => `/products/${row.original.id}`,
        orderBy: [
          { key: "title", label: t("fields.title") },
          { key: "created_at", label: t("fields.createdAt") },
          { key: "updated_at", label: t("fields.updatedAt") }
        ],
        commands: [
          {
            action: handleEdit,
            label: t("actions.edit"),
            shortcut: "e"
          },
          {
            action: handleDelete,
            label: t("actions.delete"),
            shortcut: "d"
          }
        ],
        pagination: true,
        search: true,
        prefix: PREFIX,
        queryObject: raw,
        "data-testid": "price-list-product-section-table"
      }
    )
  ] });
};
var ProductRowAction = ({
  product,
  priceList
}) => {
  const { t } = useTranslation3();
  const prompt = usePrompt();
  const { mutateAsync } = usePriceListLinkProducts(priceList.id);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("priceLists.products.delete.confirmation", {
        count: 1
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    mutateAsync(
      {
        remove: [product.id]
      },
      {
        onSuccess: () => {
          toast.success(
            t("priceLists.products.delete.successToast", {
              count: 1
            })
          );
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsx3(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx3(PencilSquare3, {}),
              label: t("priceLists.products.actions.editPrices"),
              to: `products/edit?ids[]=${product.id}`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx3(Trash2, {}),
              label: t("actions.remove"),
              onClick: handleDelete
            }
          ]
        }
      ]
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = (priceList) => {
  const base = useProductTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base,
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => /* @__PURE__ */ jsx3(ProductRowAction, { product: row.original, priceList })
      })
    ],
    [base, priceList]
  );
};

// src/pages/price-lists/price-list-detail/price-list-detail.tsx
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const { id } = useParams();
  const { price_list, isLoading, isError, error } = usePriceList(id);
  if (isLoading || !price_list) {
    return /* @__PURE__ */ jsx4(TwoColumnPageSkeleton, { mainSections: 2, sidebarSections: 1, showJSON: true });
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx4(TwoColumnPage, { data: price_list, showJSON: true, "data-testid": "price-list-detail-page", children }) : /* @__PURE__ */ jsxs4(TwoColumnPage, { data: price_list, showJSON: true, "data-testid": "price-list-detail-page", children: [
    /* @__PURE__ */ jsxs4(TwoColumnPage.Main, { children: [
      /* @__PURE__ */ jsx4(PriceListGeneralSection, { priceList: price_list }),
      /* @__PURE__ */ jsx4(PriceListProductSection, { priceList: price_list })
    ] }),
    /* @__PURE__ */ jsx4(TwoColumnPage.Sidebar, { children: /* @__PURE__ */ jsx4(PriceListConfigurationSection, { priceList: price_list }) })
  ] });
};
var PriceListDetailPage = Object.assign(Root, {
  Main: TwoColumnPage.Main,
  Sidebar: TwoColumnPage.Sidebar,
  MainGeneralSection: PriceListGeneralSection,
  MainProductSection: PriceListProductSection,
  SidebarConfigurationSection: PriceListConfigurationSection
});

export {
  PriceListDetailPage
};
