import {
  ConfigurableDataTable,
  createTableAdapter,
  productColumnAdapter
} from "./chunk-OLKB5HXC.mjs";
import "./chunk-5LFJGD27.mjs";
import "./chunk-EJWRAUTW.mjs";
import "./chunk-NTEWUH4C.mjs";
import "./chunk-INE2QCSC.mjs";
import {
  useProductTableColumns
} from "./chunk-4AKNAVPX.mjs";
import "./chunk-V2CZ23VK.mjs";
import "./chunk-IQBAUTU5.mjs";
import "./chunk-ADOCJB6L.mjs";
import "./chunk-X6BAAGCL.mjs";
import "./chunk-P3UUX2T6.mjs";
import "./chunk-LQTHYS2Z.mjs";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TWTWTDT.mjs";
import "./chunk-HQKGZADC.mjs";
import "./chunk-EMIHDNB7.mjs";
import "./chunk-DK4WIVY6.mjs";
import {
  useProductTableQuery
} from "./chunk-R65S6ZZV.mjs";
import {
  useProductTableFilters
} from "./chunk-Q6PYDJZC.mjs";
import "./chunk-XRM7PIRS.mjs";
import {
  SingleColumnPage
} from "./chunk-GIZFNLKK.mjs";
import {
  useDataTableDateFilters
} from "./chunk-V2OKIIO7.mjs";
import "./chunk-327JQRJK.mjs";
import "./chunk-C76H5USB.mjs";
import "./chunk-3BQAAPDR.mjs";
import "./chunk-MNXC6Q4F.mjs";
import "./chunk-DG7J63J2.mjs";
import {
  useFeatureFlag
} from "./chunk-PJU3RODH.mjs";
import {
  useExtension
} from "./chunk-C5P5PL3E.mjs";
import "./chunk-LPEUYMRK.mjs";
import {
  ActionMenu
} from "./chunk-OZPB6JBL.mjs";
import "./chunk-OC7BQLYI.mjs";
import "./chunk-S4DMV3ZT.mjs";
import "./chunk-QJ63TWAK.mjs";
import {
  useProductTags
} from "./chunk-OW2UL5FI.mjs";
import "./chunk-5DUV4AET.mjs";
import "./chunk-FAB3VINY.mjs";
import "./chunk-Q7YBE4IP.mjs";
import "./chunk-HI6URQ7H.mjs";
import "./chunk-6CLQKVAU.mjs";
import "./chunk-KI7TOXBR.mjs";
import {
  useProductTypes
} from "./chunk-QBIQEVTU.mjs";
import "./chunk-WAXMT4IY.mjs";
import "./chunk-DYDGGABK.mjs";
import "./chunk-LGNTHZ5Y.mjs";
import "./chunk-CN7JXSGW.mjs";
import "./chunk-AO2USOOE.mjs";
import "./chunk-KWWLGCSY.mjs";
import "./chunk-5AFMB7XQ.mjs";
import "./chunk-5U6AZEO7.mjs";
import "./chunk-A63RZVX6.mjs";
import "./chunk-HBXV7ENS.mjs";
import "./chunk-ZBMENGLV.mjs";
import "./chunk-LGLPAUIO.mjs";
import "./chunk-CDORR33H.mjs";
import "./chunk-DE44HCDH.mjs";
import {
  useSalesChannels
} from "./chunk-MUOBXNL6.mjs";
import "./chunk-BEQ5XTWH.mjs";
import "./chunk-HP2JH45P.mjs";
import "./chunk-VCSSQVPD.mjs";
import "./chunk-SQDIZZDW.mjs";
import {
  productsQueryKeys,
  useDeleteProduct,
  useProducts
} from "./chunk-LA2ILUXH.mjs";
import "./chunk-7AXHHXCX.mjs";
import {
  queryClient
} from "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import {
  sdk
} from "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

// src/routes/products/product-list/loader.ts
var productsListQuery = () => ({
  queryKey: productsQueryKeys.list({
    limit: 20,
    offset: 0,
    is_giftcard: false
  }),
  queryFn: async () => sdk.admin.product.list({ limit: 20, offset: 0, is_giftcard: false })
});
var productsLoader = (client) => {
  return async () => {
    const query = productsListQuery();
    return queryClient.getQueryData(
      query.queryKey
    ) ?? await client.fetchQuery(query);
  };
};

// src/routes/products/product-list/components/product-list-table/product-list-table.tsx
import { GlobeEurope, PencilSquare, Trash } from "@medusajs/icons";
import { Button, Container, Heading, toast, usePrompt } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Link, Outlet, useLoaderData, useLocation } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var ProductListTable = () => {
  const { t } = useTranslation();
  const location = useLocation();
  const initialData = useLoaderData();
  const { searchParams, raw } = useProductTableQuery({ pageSize: PAGE_SIZE });
  const { products, count, isLoading, isError, error } = useProducts(
    {
      ...searchParams,
      is_giftcard: false
    },
    {
      initialData,
      placeholderData: keepPreviousData
    }
  );
  const filters = useProductTableFilters();
  const columns = useColumns();
  const { table } = useDataTable({
    data: products ?? [],
    columns,
    count,
    enablePagination: true,
    pageSize: PAGE_SIZE,
    getRowId: (row) => row.id
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx(Heading, { level: "h1", children: t("products.domain") }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-x-2", children: [
        /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", asChild: true, children: /* @__PURE__ */ jsx(Link, { to: `export${location.search}`, children: t("actions.export") }) }),
        /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", asChild: true, children: /* @__PURE__ */ jsx(Link, { to: `import${location.search}`, children: t("actions.import") }) }),
        /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", asChild: true, children: /* @__PURE__ */ jsx(Link, { to: "create", children: t("actions.create") }) })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      _DataTable,
      {
        table,
        columns,
        count,
        pageSize: PAGE_SIZE,
        filters,
        search: true,
        pagination: true,
        isLoading,
        queryObject: raw,
        navigateTo: (row) => `${row.original.id}`,
        orderBy: [
          { key: "title", label: t("fields.title") },
          { key: "created_at", label: t("fields.createdAt") },
          { key: "updated_at", label: t("fields.updatedAt") }
        ],
        noRecords: {
          message: t("products.list.noRecordsMessage")
        }
      }
    ),
    /* @__PURE__ */ jsx(Outlet, {})
  ] });
};
var ProductActions = ({ product }) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const { mutateAsync } = useDeleteProduct(product.id);
  const isTranslationsEnabled = useFeatureFlag("translation");
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("products.deleteWarning", {
        title: product.title
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(void 0, {
      onSuccess: () => {
        toast.success(t("products.toasts.delete.success.header"), {
          description: t("products.toasts.delete.success.description", {
            title: product.title
          })
        });
      },
      onError: (e) => {
        toast.error(t("products.toasts.delete.error.header"), {
          description: e.message
        });
      }
    });
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(PencilSquare, {}),
              label: t("actions.edit"),
              to: `/products/${product.id}/edit`
            }
          ]
        },
        ...isTranslationsEnabled ? [
          {
            actions: [
              {
                icon: /* @__PURE__ */ jsx(GlobeEurope, {}),
                label: t("translations.actions.manage"),
                to: `/settings/translations/edit?reference=product&reference_id=${product.id}`
              }
            ]
          }
        ] : [],
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(Trash, {}),
              label: t("actions.delete"),
              onClick: handleDelete
            }
          ]
        }
      ]
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useProductTableColumns();
  const columns = useMemo(
    () => [
      ...base,
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(ProductActions, { product: row.original });
        }
      })
    ],
    [base]
  );
  return columns;
};

// src/routes/products/product-list/components/product-list-table/configurable-product-list-table.tsx
import { useTranslation as useTranslation3 } from "react-i18next";
import { Outlet as Outlet2, useLocation as useLocation2 } from "react-router-dom";

// src/routes/products/product-list/components/product-list-table/use-product-table-filters.tsx
import { useMemo as useMemo2 } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { createDataTableFilterHelper } from "@medusajs/ui";
var filterHelper = createDataTableFilterHelper();
var useProductTableFilters2 = () => {
  const { t } = useTranslation2();
  const dateFilters = useDataTableDateFilters();
  const { product_types } = useProductTypes({
    limit: 1e3,
    offset: 0
  });
  const { product_tags } = useProductTags({
    limit: 1e3,
    offset: 0
  });
  const { sales_channels } = useSalesChannels({
    limit: 1e3,
    fields: "id,name"
  });
  return useMemo2(() => {
    const filters = [...dateFilters];
    if (product_types?.length) {
      filters.push(
        filterHelper.accessor("type_id", {
          label: t("fields.type"),
          type: "multiselect",
          options: product_types.map((t2) => ({
            label: t2.value,
            value: t2.id
          }))
        })
      );
    }
    if (product_tags?.length) {
      filters.push(
        filterHelper.accessor("tag_id", {
          label: t("fields.tag"),
          type: "multiselect",
          options: product_tags.map((t2) => ({
            label: t2.value,
            value: t2.id
          }))
        })
      );
    }
    if (sales_channels?.length) {
      filters.push(
        filterHelper.accessor("sales_channel_id", {
          label: t("fields.salesChannel"),
          type: "multiselect",
          options: sales_channels.map((s) => ({
            label: s.name,
            value: s.id
          }))
        })
      );
    }
    filters.push(
      filterHelper.accessor("status", {
        label: t("fields.status"),
        type: "multiselect",
        options: [
          {
            label: t("products.productStatus.draft"),
            value: "draft"
          },
          {
            label: t("products.productStatus.proposed"),
            value: "proposed"
          },
          {
            label: t("products.productStatus.published"),
            value: "published"
          },
          {
            label: t("products.productStatus.rejected"),
            value: "rejected"
          }
        ]
      })
    );
    return filters;
  }, [product_types, product_tags, sales_channels, dateFilters, t]);
};

// src/routes/products/product-list/components/product-list-table/product-table-adapter.tsx
function createProductTableAdapter() {
  return createTableAdapter({
    entity: "products",
    queryPrefix: "p",
    pageSize: 20,
    columnAdapter: productColumnAdapter,
    useData: (fields, params) => {
      const { products, count, isError, error, isLoading } = useProducts(
        {
          fields,
          ...params,
          is_giftcard: false
          // Exclude gift cards from product list
        },
        {
          placeholderData: (previousData, previousQuery) => {
            const prevFields = previousQuery?.[previousQuery?.length - 1]?.query?.fields;
            if (prevFields && prevFields !== fields) {
              return void 0;
            }
            return previousData;
          }
        }
      );
      return { data: products, count, isLoading, isError, error };
    },
    getRowHref: (row) => `/products/${row.id}`
  });
}
function useProductTableAdapter() {
  const filters = useProductTableFilters2();
  const adapter = createProductTableAdapter();
  return {
    ...adapter,
    filters
  };
}

// src/routes/products/product-list/components/product-list-table/configurable-product-list-table.tsx
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var ConfigurableProductListTable = () => {
  const { t } = useTranslation3();
  const location = useLocation2();
  const adapter = useProductTableAdapter();
  return /* @__PURE__ */ jsxs2(Fragment, { children: [
    /* @__PURE__ */ jsx2(
      ConfigurableDataTable,
      {
        adapter,
        heading: t("products.domain"),
        actions: [
          { label: t("actions.export"), to: `export${location.search}` },
          { label: t("actions.import"), to: `import${location.search}` },
          { label: t("actions.create"), to: "create" }
        ]
      }
    ),
    /* @__PURE__ */ jsx2(Outlet2, {})
  ] });
};

// src/routes/products/product-list/product-list.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var ProductList = () => {
  const { getWidgets } = useExtension();
  const isViewConfigEnabled = useFeatureFlag("view_configurations");
  return /* @__PURE__ */ jsx3(
    SingleColumnPage,
    {
      widgets: {
        after: getWidgets("product.list.after"),
        before: getWidgets("product.list.before")
      },
      children: isViewConfigEnabled ? /* @__PURE__ */ jsx3(ConfigurableProductListTable, {}) : /* @__PURE__ */ jsx3(ProductListTable, {})
    }
  );
};
export {
  ProductList as Component,
  productsLoader as productLoader
};
