import {
  useCurrenciesTableColumns,
  useCurrenciesTableQuery
} from "./chunk-64XMEZ5A.js";
import {
  StatusCell
} from "./chunk-DB6ANJBO.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import {
  SingleColumnPage
} from "./chunk-XIZLPYEE.js";
import {
  SingleColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useCurrencies
} from "./chunk-FNBKEF54.js";
import {
  useStockLocation
} from "./chunk-OFKUNYQJ.js";
import {
  useRegion
} from "./chunk-W5UPPL3W.js";
import {
  useStore,
  useUpdateStore
} from "./chunk-LC6TM5OT.js";
import {
  usePricePreferences
} from "./chunk-7SJC6BWZ.js";
import {
  useSalesChannel
} from "./chunk-N4JU7GWK.js";

// src/pages/marketplace/marketplace-detail/marketplace-detail.tsx
import { Children } from "react";
import { useLoaderData } from "react-router-dom";

// src/pages/marketplace/marketplace-detail/components/marketplace-currency-section/marketplace-currency-section.tsx
import { CheckCircle, Plus, Trash, XCircle } from "@medusajs/icons";
import {
  Checkbox,
  CommandBar,
  Container,
  Heading,
  toast,
  usePrompt
} from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var MarketplaceCurrencySection = ({ store }) => {
  const [rowSelection, setRowSelection] = useState({});
  const { searchParams, raw } = useCurrenciesTableQuery({ pageSize: PAGE_SIZE });
  const {
    currencies,
    count,
    isPending: isCurrenciesPending,
    isError: isCurrenciesError,
    error: currenciesError
  } = useCurrencies(
    {
      code: store.supported_currencies?.map((c) => c.currency_code),
      ...searchParams
    },
    {
      placeholderData: keepPreviousData,
      enabled: !!store.supported_currencies?.length
    }
  );
  const {
    price_preferences: pricePreferences,
    isPending: isPricePreferencesPending,
    isError: isPricePreferencesError,
    error: pricePreferencesError
  } = usePricePreferences(
    {
      attribute: "currency_code",
      value: store.supported_currencies?.map((c) => c.currency_code)
    },
    {
      enabled: !!store.supported_currencies?.length
    }
  );
  const columns = useColumns();
  const prefMap = useMemo(() => {
    return new Map(pricePreferences?.map((pref) => [pref.value, pref]));
  }, [pricePreferences]);
  const withTaxInclusivity = currencies?.map((c) => ({
    ...c,
    is_tax_inclusive: prefMap.get(c.code)?.is_tax_inclusive
  }));
  const { table } = useDataTable({
    data: withTaxInclusivity ?? [],
    columns,
    count,
    getRowId: (row) => row.code,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    meta: {
      storeId: store.id,
      supportedCurrencies: store.supported_currencies,
      defaultCurrencyCode: store.supported_currencies?.find((c) => c.is_default)?.currency_code,
      preferencesMap: prefMap
    }
  });
  const { mutateAsync } = useUpdateStore(store.id);
  const { t } = useTranslation();
  const prompt = usePrompt();
  const handleDeleteCurrencies = async () => {
    const ids = Object.keys(rowSelection);
    const result = await prompt({
      title: t("general.areYouSure"),
      description: t("store.removeCurrencyWarning", {
        count: ids.length
      }),
      confirmText: t("actions.remove"),
      cancelText: t("actions.cancel")
    });
    if (!result) {
      return;
    }
    await mutateAsync(
      {
        supported_currencies: store.supported_currencies?.filter(
          (c) => !ids.includes(c.currency_code)
        ) ?? []
      },
      {
        onSuccess: () => {
          setRowSelection({});
          toast.success(t("store.toast.currenciesRemoved"));
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  if (isCurrenciesError) {
    throw currenciesError;
  }
  if (isPricePreferencesError) {
    throw pricePreferencesError;
  }
  const isLoading = isCurrenciesPending || isPricePreferencesPending;
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", "data-testid": "store-currency-section-container", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "store-currency-section-header", children: [
      /* @__PURE__ */ jsx(Heading, { level: "h2", "data-testid": "store-currency-section-heading", children: t("store.currencies") }),
      /* @__PURE__ */ jsx(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx(Plus, {}),
                  label: t("actions.add"),
                  to: "currencies"
                }
              ]
            }
          ],
          "data-testid": "store-currency-section-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      _DataTable,
      {
        orderBy: [
          { key: "name", label: t("fields.name") },
          { key: "code", label: t("fields.code") }
        ],
        search: true,
        pagination: true,
        table,
        pageSize: PAGE_SIZE,
        columns,
        count: !store.supported_currencies?.length ? 0 : count,
        isLoading: !store.supported_currencies?.length ? false : isLoading,
        queryObject: raw,
        "data-testid": "store-currency-section-table"
      }
    ),
    /* @__PURE__ */ jsx(CommandBar, { open: !!Object.keys(rowSelection).length, "data-testid": "store-currency-section-command-bar", children: /* @__PURE__ */ jsxs(CommandBar.Bar, { "data-testid": "store-currency-section-command-bar-bar", children: [
      /* @__PURE__ */ jsx(CommandBar.Value, { "data-testid": "store-currency-section-command-bar-value", children: t("general.countSelected", {
        count: Object.keys(rowSelection).length
      }) }),
      /* @__PURE__ */ jsx(CommandBar.Seperator, {}),
      /* @__PURE__ */ jsx(
        CommandBar.Command,
        {
          action: handleDeleteCurrencies,
          shortcut: "r",
          label: t("actions.remove"),
          "data-testid": "store-currency-section-command-bar-remove"
        }
      )
    ] }) })
  ] });
};
var CurrencyActions = ({
  storeId,
  currency,
  supportedCurrencies,
  defaultCurrencyCode,
  preferencesMap
}) => {
  const { mutateAsync } = useUpdateStore(storeId);
  const { t } = useTranslation();
  const prompt = usePrompt();
  const handleRemove = async () => {
    const result = await prompt({
      title: t("general.areYouSure"),
      description: t("store.removeCurrencyWarning", {
        count: 1
      }),
      verificationInstruction: t("general.typeToConfirm"),
      verificationText: currency.name,
      confirmText: t("actions.remove"),
      cancelText: t("actions.cancel")
    });
    if (!result) {
      return;
    }
    await mutateAsync(
      {
        supported_currencies: supportedCurrencies.filter(
          (c) => c.currency_code !== currency.code
        )
      },
      {
        onSuccess: () => {
          toast.success(t("store.toast.currenciesRemoved"));
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  const handleToggleTaxInclusivity = async () => {
    await mutateAsync(
      {
        supported_currencies: supportedCurrencies.map((c) => {
          const pref = preferencesMap.get(c.currency_code);
          return {
            ...c,
            is_tax_inclusive: c.currency_code === currency.code ? !pref?.is_tax_inclusive : void 0
          };
        })
      },
      {
        onSuccess: () => {
          toast.success(t("store.toast.updatedTaxInclusivitySuccessfully"));
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: preferencesMap.get(currency.code)?.is_tax_inclusive ? /* @__PURE__ */ jsx(XCircle, {}) : /* @__PURE__ */ jsx(CheckCircle, {}),
              label: preferencesMap.get(currency.code)?.is_tax_inclusive ? t("store.disableTaxInclusivePricing") : t("store.enableTaxInclusivePricing"),
              onClick: handleToggleTaxInclusivity
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(Trash, {}),
              label: t("actions.remove"),
              onClick: handleRemove,
              disabled: currency.code === defaultCurrencyCode
            }
          ]
        }
      ],
      "data-testid": `store-currency-section-action-menu-${currency.code}`
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useCurrenciesTableColumns();
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value),
              "data-testid": "store-currency-section-select-all-checkbox"
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `store-currency-section-select-checkbox-${row.original.code}`
            }
          );
        }
      }),
      ...base,
      columnHelper.accessor("is_tax_inclusive", {
        header: t("fields.taxInclusivePricing"),
        cell: ({ getValue }) => {
          const isTaxInclusive = getValue();
          return /* @__PURE__ */ jsx(StatusCell, { color: isTaxInclusive ? "green" : "grey", children: isTaxInclusive ? t("fields.true") : t("fields.false") });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row, table }) => {
          const {
            supportedCurrencies,
            storeId,
            defaultCurrencyCode,
            preferencesMap
          } = table.options.meta;
          return /* @__PURE__ */ jsx(
            CurrencyActions,
            {
              storeId,
              currency: row.original,
              supportedCurrencies,
              defaultCurrencyCode,
              preferencesMap
            }
          );
        }
      })
    ],
    [base, t]
  );
};

// src/pages/marketplace/marketplace-detail/components/marketplace-general-section/marketplace-general-section.tsx
import { PencilSquare } from "@medusajs/icons";
import { Badge, Container as Container2, Heading as Heading2, Text } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { Link } from "react-router-dom";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var MarketplaceGeneralSection = ({ store }) => {
  const { t } = useTranslation2();
  const { region } = useRegion(store.default_region_id, void 0, {
    enabled: !!store.default_region_id
  });
  const defaultCurrency = store.supported_currencies?.find((c) => c.is_default);
  const { sales_channel } = useSalesChannel(store.default_sales_channel_id, {
    enabled: !!store.default_sales_channel_id
  });
  const { stock_location } = useStockLocation(
    store.default_location_id,
    {
      fields: "id,name"
    },
    {
      enabled: !!store.default_location_id
    }
  );
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", "data-testid": "store-general-section-container", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "store-general-section-header", children: [
      /* @__PURE__ */ jsxs2("div", { children: [
        /* @__PURE__ */ jsx2(Heading2, { "data-testid": "store-general-section-heading", children: t("marketplace.domain") }),
        /* @__PURE__ */ jsx2(Text, { className: "text-ui-fg-subtle", size: "small", "data-testid": "store-general-section-subtitle", children: t("marketplace.manageMarketplaceDetails") })
      ] }),
      /* @__PURE__ */ jsx2(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx2(PencilSquare, {}),
                  label: t("actions.edit"),
                  to: "edit"
                }
              ]
            }
          ],
          "data-testid": "store-general-section-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", "data-testid": "store-general-section-name", children: [
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": "store-general-section-name-label", children: t("fields.name") }),
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", "data-testid": "store-general-section-name-value", children: store.name })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", "data-testid": "store-general-section-currency", children: [
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": "store-general-section-currency-label", children: t("store.defaultCurrency") }),
      defaultCurrency ? /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-2", "data-testid": "store-general-section-currency-value", children: [
        /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", "data-testid": "store-general-section-currency-badge", children: defaultCurrency.currency_code?.toUpperCase() }),
        /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", "data-testid": "store-general-section-currency-name", children: defaultCurrency.currency?.name })
      ] }) : /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", "data-testid": "store-general-section-currency-value", children: "-" })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", "data-testid": "store-general-section-region", children: [
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": "store-general-section-region-label", children: t("store.defaultRegion") }),
      /* @__PURE__ */ jsx2("div", { className: "flex items-center gap-x-2", "data-testid": "store-general-section-region-value", children: region ? /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", asChild: true, children: /* @__PURE__ */ jsx2(Link, { to: `/settings/regions/${region.id}`, "data-testid": "store-general-section-region-link", children: region.name }) }) : /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", children: "-" }) })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", "data-testid": "store-general-section-sales-channel", children: [
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": "store-general-section-sales-channel-label", children: t("store.defaultSalesChannel") }),
      /* @__PURE__ */ jsx2("div", { className: "flex items-center gap-x-2", "data-testid": "store-general-section-sales-channel-value", children: sales_channel ? /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", asChild: true, children: /* @__PURE__ */ jsx2(Link, { to: `/settings/sales-channels/${sales_channel.id}`, "data-testid": "store-general-section-sales-channel-link", children: sales_channel.name }) }) : /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", children: "-" }) })
    ] }),
    /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", "data-testid": "store-general-section-location", children: [
      /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": "store-general-section-location-label", children: t("store.defaultLocation") }),
      /* @__PURE__ */ jsx2("div", { className: "flex items-center gap-x-2", "data-testid": "store-general-section-location-value", children: stock_location ? /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", asChild: true, children: /* @__PURE__ */ jsx2(Link, { to: `/settings/locations/${stock_location.id}`, "data-testid": "store-general-section-location-link", children: stock_location.name }) }) : /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", children: "-" }) })
    ] })
  ] });
};

// src/pages/marketplace/marketplace-detail/marketplace-detail.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { store, isPending, isError, error } = useStore(void 0, {
    initialData
  });
  if (isPending || !store) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { sections: 2, showJSON: true, showMetadata: true });
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(SingleColumnPage, { data: store, hasOutlet: true, showMetadata: true, showJSON: true, children }) : /* @__PURE__ */ jsxs3(SingleColumnPage, { data: store, hasOutlet: true, showMetadata: true, showJSON: true, children: [
    /* @__PURE__ */ jsx3(MarketplaceGeneralSection, { store }),
    /* @__PURE__ */ jsx3(MarketplaceCurrencySection, { store })
  ] });
};
var MarketplaceDetailPage = Object.assign(Root, {
  GeneralSection: MarketplaceGeneralSection,
  CurrencySection: MarketplaceCurrencySection
});

export {
  MarketplaceDetailPage
};
