import {
  OFFERS_PAGE_SIZE,
  OFFER_PRODUCT_LIST_FIELDS
} from "./chunk-XQUF3WIS.js";
import {
  CategoryCell,
  CategoryHeader,
  ProductStatusCell,
  ProductStatusHeader
} from "./chunk-G64YUZSL.js";
import {
  ProductCell
} from "./chunk-FWPGOIFA.js";
import {
  useProductTableFilters
} from "./chunk-LFX6R456.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  SingleColumnPage
} from "./chunk-YV6MK4PZ.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useBulkDeleteOffers
} from "./chunk-5DKUSZQ7.js";
import {
  useProducts
} from "./chunk-YAUGB4LD.js";

// src/pages/offers/offer-list-page.tsx
import { Children as Children2 } from "react";
import { WidgetZone } from "@mercurjs/dashboard-shared";

// src/pages/offers/_components/offer-list-table.tsx
import { Container } from "@medusajs/ui";
import { Children } from "react";
import { Outlet } from "react-router-dom";

// src/pages/offers/_components/offer-list-data-table.tsx
import { keepPreviousData } from "@tanstack/react-query";
import { useMemo as useMemo2 } from "react";
import { useTranslation as useTranslation3 } from "react-i18next";
import { useExtendableTable } from "@mercurjs/dashboard-shared";

// src/pages/offers/_components/use-offer-table-columns.tsx
import { Text } from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/offers/_components/offer-actions.tsx
import { Buildings, CurrencyDollar, Trash } from "@medusajs/icons";
import { toast, usePrompt } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { jsx } from "react/jsx-runtime";
var OfferActions = ({ product }) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const { mutateAsync: bulkDelete } = useBulkDeleteOffers();
  const handleDelete = async () => {
    if (!product.offerIds.length) {
      return;
    }
    const confirmed = await prompt({
      title: t("general.areYouSure"),
      // The product listing is one offer to the seller, regardless of how
      // many of its variants are offered under the hood.
      description: t("offers.delete.descriptionByName", { name: product.title }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel"),
      variant: "danger"
    });
    if (!confirmed) {
      return;
    }
    const result = await bulkDelete(product.offerIds);
    if (result.failed.length === 0) {
      toast.success(t("offers.delete.successToast"));
    } else {
      toast.warning(
        t("offers.bulkDelete.partialToast", {
          succeeded: result.succeeded.length,
          total: product.offerIds.length,
          failed: result.failed.length
        })
      );
    }
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(CurrencyDollar, {}),
              label: t("offers.actions.edit_prices"),
              to: `${product.id}/edit-price`
            },
            {
              icon: /* @__PURE__ */ jsx(Buildings, {}),
              label: t("offers.actions.edit_stock_levels"),
              to: `${product.id}/edit-stock`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(Trash, {}),
              label: t("actions.delete"),
              onClick: handleDelete,
              disabled: product.offerIds.length === 0
            }
          ]
        }
      ]
    }
  );
};

// src/pages/offers/_components/use-offer-table-columns.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var countOfferedVariants = (row) => (row.variants ?? []).filter((v) => (v.offers?.length ?? 0) > 0).length;
var collectOfferIds = (row) => (row.variants ?? []).flatMap((v) => (v.offers ?? []).map((o) => o.id));
var useOfferTableColumns = () => {
  const { t } = useTranslation2();
  return useMemo(
    () => [
      columnHelper.display({
        id: "product",
        header: t("offers.domain"),
        cell: ({ row }) => /* @__PURE__ */ jsx2(
          ProductCell,
          {
            product: {
              title: row.original.title ?? "",
              thumbnail: row.original.thumbnail ?? null
            }
          }
        )
      }),
      columnHelper.display({
        id: "categories",
        header: () => /* @__PURE__ */ jsx2(CategoryHeader, {}),
        cell: ({ row }) => /* @__PURE__ */ jsx2(CategoryCell, { categories: row.original.categories })
      }),
      columnHelper.display({
        id: "collection",
        header: t("fields.collection"),
        cell: ({ row }) => {
          const collection = row.original.collection;
          if (!collection?.title) return /* @__PURE__ */ jsx2(PlaceholderCell, {});
          return /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", className: "truncate", children: collection.title });
        }
      }),
      columnHelper.display({
        id: "variants",
        header: t("offers.fields.variants"),
        cell: ({ row }) => /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", className: "truncate", children: t("offers.fields.variantsCount", {
          count: countOfferedVariants(row.original)
        }) })
      }),
      columnHelper.display({
        id: "status",
        header: () => /* @__PURE__ */ jsx2(ProductStatusHeader, {}),
        cell: ({ row }) => {
          const status = row.original.status;
          if (!status) return /* @__PURE__ */ jsx2(PlaceholderCell, {});
          return /* @__PURE__ */ jsx2(ProductStatusCell, { status });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => /* @__PURE__ */ jsx2(
          OfferActions,
          {
            product: {
              id: row.original.id,
              title: row.original.title ?? "",
              offerIds: collectOfferIds(row.original)
            }
          }
        )
      })
    ],
    [t]
  );
};

// src/pages/offers/_components/use-offer-table-filters.tsx
var useOfferTableFilters = () => useProductTableFilters();

// src/pages/offers/_components/use-offer-table-query.tsx
import { useLinkQuery } from "@mercurjs/dashboard-shared";
var useOfferTableQuery = ({
  pageSize = 10,
  prefix
}) => {
  const raw = useQueryParams(
    [
      "q",
      "order",
      "offset",
      "created_at",
      "updated_at",
      "category_id",
      "collection_id",
      "type_id",
      "tag_id",
      "status",
      "id"
    ],
    prefix
  );
  const {
    offset,
    created_at,
    updated_at,
    category_id,
    collection_id,
    type_id,
    tag_id,
    status,
    order,
    q
  } = raw;
  const { fields } = useLinkQuery("offer", OFFER_PRODUCT_LIST_FIELDS);
  const searchParams = {
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    order: order || "title",
    q,
    category_id: category_id ? category_id.split(",") : void 0,
    collection_id: collection_id ? collection_id.split(",") : void 0,
    type_id: type_id ? type_id.split(",") : void 0,
    tag_id: tag_id ? tag_id.split(",") : void 0,
    status: status ? status.split(",") : void 0,
    created_at: created_at ? JSON.parse(created_at) : void 0,
    updated_at: updated_at ? JSON.parse(updated_at) : void 0,
    has_offer: "true",
    fields
  };
  return {
    searchParams,
    raw
  };
};

// src/pages/offers/_components/offer-list-data-table.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var OfferListDataTable = () => {
  const { t } = useTranslation3();
  const { raw, searchParams } = useOfferTableQuery({
    pageSize: OFFERS_PAGE_SIZE
  });
  const { products, count, isLoading, isError, error } = useProducts(
    searchParams,
    { placeholderData: keepPreviousData }
  );
  const rows = products ?? [];
  const baseFilters = useOfferTableFilters();
  const { columns, filters: extFilters } = useColumns();
  const filters = useMemo2(
    () => [...baseFilters, ...extFilters],
    [baseFilters, extFilters]
  );
  const { table } = useDataTable({
    data: rows,
    columns,
    count,
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: OFFERS_PAGE_SIZE
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx3(
    _DataTable,
    {
      table,
      columns,
      pageSize: OFFERS_PAGE_SIZE,
      count,
      isLoading,
      pagination: true,
      search: true,
      filters,
      queryObject: raw,
      orderBy: [
        { key: "title", label: t("fields.title") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      defaultOrderBy: "title",
      navigateTo: (row) => `${row.original.id}`,
      noRecords: {
        title: t("offers.empty.heading"),
        message: t("offers.empty.description"),
        action: {
          to: "create",
          label: t("offers.actions.create")
        }
      }
    }
  );
};
var useColumns = () => {
  const base = useOfferTableColumns();
  const actionsColumn = base[base.length - 1];
  const baseColumns = base.slice(0, -1);
  const { columns: extended, filters } = useExtendableTable({
    model: "offer",
    columns: baseColumns
  });
  const columns = useMemo2(
    () => [...extended, actionsColumn],
    [extended, actionsColumn]
  );
  return { columns, filters };
};

// src/pages/offers/_components/offer-list-header.tsx
import { Button, Heading } from "@medusajs/ui";
import { useTranslation as useTranslation4 } from "react-i18next";
import { Link } from "react-router-dom";
import { jsx as jsx4, jsxs } from "react/jsx-runtime";
var OfferListTitle = () => {
  const { t } = useTranslation4();
  return /* @__PURE__ */ jsx4(Heading, { children: t("offers.domain") });
};
var OfferListActions = () => {
  const { t } = useTranslation4();
  return /* @__PURE__ */ jsx4(Button, { size: "small", variant: "secondary", asChild: true, children: /* @__PURE__ */ jsx4(Link, { to: "create", "data-testid": "offer-list-create-button", children: t("offers.actions.create") }) });
};
var OfferListHeader = () => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
  /* @__PURE__ */ jsx4(OfferListTitle, {}),
  /* @__PURE__ */ jsx4(OfferListActions, {})
] });

// src/pages/offers/_components/offer-list-table.tsx
import { Fragment, jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
var OfferListTable = ({ children }) => /* @__PURE__ */ jsxs2(Container, { className: "divide-y p-0", "data-testid": "offer-list-table", children: [
  Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs2(Fragment, { children: [
    /* @__PURE__ */ jsx5(OfferListHeader, {}),
    /* @__PURE__ */ jsx5(OfferListDataTable, {})
  ] }),
  /* @__PURE__ */ jsx5(Outlet, {})
] });

// src/pages/offers/offer-list-page.tsx
import { jsx as jsx6 } from "react/jsx-runtime";
var Root = ({ children }) => /* @__PURE__ */ jsx6(SingleColumnPage, { children: /* @__PURE__ */ jsx6(WidgetZone, { id: "offers.list", children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx6(OfferListTable, {}) }) });
var OfferListPage = Object.assign(Root, {
  Table: OfferListTable,
  Header: OfferListHeader,
  HeaderTitle: OfferListTitle,
  HeaderActions: OfferListActions,
  DataTable: OfferListDataTable
});

export {
  OfferListPage
};
