import {
  OFFER_PRODUCT_DETAIL_FIELDS
} from "./chunk-XQUF3WIS.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  ProductMediaSection,
  productStatusColor
} from "./chunk-WN2NWWVO.js";
import {
  SectionRow
} from "./chunk-4TLP3TAA.js";
import {
  TwoColumnPage
} from "./chunk-YV6MK4PZ.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import {
  TwoColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import {
  useBulkDeleteOffers
} from "./chunk-5DKUSZQ7.js";
import {
  useProduct
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/offers/[id]/offer-detail-page.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";
import { useLinkQuery, WidgetZone } from "@mercurjs/dashboard-shared";

// src/pages/offers/[id]/_components/offer-detail-general-section.tsx
import { Trash } from "@medusajs/icons";
import { Container, Heading, StatusBadge, toast, usePrompt } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { DisplayExtensionZone, DisplayField } from "@mercurjs/dashboard-shared";
import { jsx, jsxs } from "react/jsx-runtime";
var GENERAL_FIELD_IDS = [
  "title",
  "status",
  "description",
  "subtitle",
  "handle",
  "discountable"
];
var OfferDetailGeneralSection = ({
  product
}) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const navigate = useNavigate();
  const { mutateAsync: bulkDelete } = useBulkDeleteOffers();
  const offerIds = (product.variants ?? []).flatMap(
    (v) => (v.offers ?? []).map((o) => o.id)
  );
  const handleDelete = async () => {
    if (!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.bulkDelete.description", { count: 1 }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel"),
      variant: "danger"
    });
    if (!confirmed) {
      return;
    }
    const result = await bulkDelete(offerIds);
    if (result.failed.length === 0) {
      toast.success(t("offers.bulkDelete.successToast", { count: 1 }));
      navigate("/offers");
    } else {
      toast.warning(
        t("offers.bulkDelete.partialToast", {
          succeeded: result.succeeded.length,
          total: offerIds.length,
          failed: result.failed.length
        })
      );
    }
  };
  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(DisplayField, { model: "offer", zone: "general", id: "title", data: product, children: /* @__PURE__ */ jsx(Heading, { children: product.title }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-4", children: [
        product.status && /* @__PURE__ */ jsx(
          DisplayField,
          {
            model: "offer",
            zone: "general",
            id: "status",
            data: product,
            children: /* @__PURE__ */ jsx(StatusBadge, { color: productStatusColor(product.status), children: t(`products.productStatus.${product.status}`) })
          }
        ),
        /* @__PURE__ */ jsx(
          ActionMenu,
          {
            groups: [
              {
                actions: [
                  {
                    label: t("actions.delete"),
                    onClick: handleDelete,
                    icon: /* @__PURE__ */ jsx(Trash, {}),
                    disabled: offerIds.length === 0
                  }
                ]
              }
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx(DisplayField, { model: "offer", zone: "general", id: "description", data: product, children: /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: t("fields.description"),
        value: product.description || "-"
      }
    ) }),
    /* @__PURE__ */ jsx(DisplayField, { model: "offer", zone: "general", id: "subtitle", data: product, children: /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: t("fields.subtitle"),
        value: product.subtitle || "-"
      }
    ) }),
    /* @__PURE__ */ jsx(DisplayField, { model: "offer", zone: "general", id: "handle", data: product, children: /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: t("fields.handle"),
        value: product.handle ? `/${product.handle}` : "-"
      }
    ) }),
    /* @__PURE__ */ jsx(
      DisplayField,
      {
        model: "offer",
        zone: "general",
        id: "discountable",
        data: product,
        children: /* @__PURE__ */ jsx(
          SectionRow,
          {
            title: t("fields.discountable"),
            value: product.discountable ? t("general.true") : t("general.false")
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      DisplayExtensionZone,
      {
        model: "offer",
        zone: "general",
        data: product,
        builtInFieldIds: GENERAL_FIELD_IDS
      }
    )
  ] });
};

// src/pages/offers/[id]/_components/offer-variants-section.tsx
import { Buildings, Component, CurrencyDollar, PencilSquare, Trash as Trash2 } from "@medusajs/icons";
import {
  Badge,
  clx,
  Container as Container2,
  Heading as Heading2,
  toast as toast2,
  Tooltip,
  usePrompt as usePrompt2
} from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useCallback, useMemo } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useNavigate as useNavigate2 } from "react-router-dom";
import { DisplayExtensionZone as DisplayExtensionZone2 } from "@mercurjs/dashboard-shared";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var PREFIX = "ov";
var skuOf = (row) => row.offer.sku ?? row.variant.sku ?? "";
var inventoryItemIdOf = (offer) => offer.inventory_item_link?.find((link) => link.inventory_item?.id)?.inventory_item?.id ?? null;
var inventoryOf = (offer) => {
  const links = offer.inventory_item_link ?? [];
  let available = 0;
  const locations = /* @__PURE__ */ new Set();
  for (const link of links) {
    for (const level of link.inventory_item?.location_levels ?? []) {
      available += level.stocked_quantity ?? 0;
      if (level.location_id) {
        locations.add(level.location_id);
      }
    }
  }
  return {
    hasItems: links.length > 0,
    isKit: links.length > 1,
    available,
    locationCount: locations.size
  };
};
var matchesDateFilter = (value, filter) => {
  if (!value) {
    return false;
  }
  const time = new Date(value).getTime();
  if (Number.isNaN(time)) {
    return false;
  }
  if (filter.$gte && time < new Date(filter.$gte).getTime()) {
    return false;
  }
  if (filter.$lte && time > new Date(filter.$lte).getTime()) {
    return false;
  }
  return true;
};
var columnHelper = createColumnHelper();
var useColumns = ({
  optionTitles,
  thumbnail,
  onEdit,
  onDelete
}) => {
  const { t } = useTranslation2();
  return useMemo(
    () => [
      columnHelper.accessor((row) => row.variant.title ?? "", {
        id: "title",
        header: t("fields.title"),
        cell: ({ getValue }) => /* @__PURE__ */ jsxs2("div", { className: "flex h-full w-full max-w-[250px] items-center gap-x-3 overflow-hidden", children: [
          /* @__PURE__ */ jsx2("div", { className: "w-fit flex-shrink-0", children: /* @__PURE__ */ jsx2(Thumbnail, { src: thumbnail ?? null }) }),
          getValue() ? /* @__PURE__ */ jsx2("span", { title: getValue(), className: "truncate", children: getValue() }) : /* @__PURE__ */ jsx2("span", { className: "text-ui-fg-muted", children: "-" })
        ] })
      }),
      columnHelper.accessor((row) => skuOf(row), {
        id: "sku",
        header: t("fields.sku"),
        cell: ({ getValue }) => getValue() ? /* @__PURE__ */ jsx2("span", { title: getValue(), className: "truncate", children: getValue() }) : /* @__PURE__ */ jsx2(PlaceholderCell, {})
      }),
      ...optionTitles.map(
        (title) => columnHelper.display({
          id: `option-${title}`,
          header: title,
          cell: ({ row }) => {
            const opt = row.original.variant.options?.find(
              (o) => o.option?.title === title
            );
            return opt?.value ? /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", children: opt.value }) : /* @__PURE__ */ jsx2(PlaceholderCell, {});
          }
        })
      ),
      columnHelper.display({
        id: "inventory",
        header: t("fields.inventory"),
        cell: ({ row }) => {
          const { hasItems, isKit, available, locationCount } = inventoryOf(
            row.original.offer
          );
          if (!hasItems) {
            return /* @__PURE__ */ jsx2(PlaceholderCell, {});
          }
          const text = t("products.variant.tableItem", {
            availableCount: available,
            locationCount,
            count: locationCount
          });
          return /* @__PURE__ */ jsx2(Tooltip, { content: text, children: /* @__PURE__ */ jsxs2("div", { className: "flex h-full w-full items-center gap-2 overflow-hidden", children: [
            isKit && /* @__PURE__ */ jsx2(Component, { className: "text-ui-fg-subtle" }),
            /* @__PURE__ */ jsx2(
              "span",
              {
                className: clx("truncate", {
                  "text-ui-fg-error": available === 0
                }),
                children: text
              }
            )
          ] }) });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => {
          const inventoryItemId = inventoryItemIdOf(row.original.offer);
          return /* @__PURE__ */ jsx2(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    {
                      icon: /* @__PURE__ */ jsx2(PencilSquare, {}),
                      label: t("actions.edit"),
                      onClick: () => onEdit(row.original.id)
                    },
                    inventoryItemId ? {
                      icon: /* @__PURE__ */ jsx2(Buildings, {}),
                      label: t("offers.detail.goToInventoryItem"),
                      to: `/inventory/${inventoryItemId}`
                    } : {
                      icon: /* @__PURE__ */ jsx2(Buildings, {}),
                      label: t("offers.detail.goToInventoryItem"),
                      onClick: () => {
                      },
                      disabled: true,
                      disabledTooltip: t("offers.detail.noInventoryItems")
                    }
                  ]
                },
                {
                  actions: [
                    {
                      icon: /* @__PURE__ */ jsx2(Trash2, {}),
                      label: t("actions.delete"),
                      onClick: () => onDelete(row.original.id, skuOf(row.original))
                    }
                  ]
                }
              ]
            }
          );
        }
      })
    ],
    [t, optionTitles, thumbnail, onEdit, onDelete]
  );
};
var OfferVariantsSection = ({
  variants,
  thumbnail
}) => {
  const { t } = useTranslation2();
  const navigate = useNavigate2();
  const prompt = usePrompt2();
  const { mutateAsync: bulkDelete } = useBulkDeleteOffers();
  const { q, order, offset, created_at, updated_at } = useQueryParams(
    ["q", "order", "offset", "created_at", "updated_at"],
    PREFIX
  );
  const allRows = useMemo(
    () => (variants ?? []).flatMap(
      (variant) => (variant.offers ?? []).map((offer) => ({
        id: offer.id,
        variant,
        offer
      }))
    ),
    [variants]
  );
  const optionTitles = useMemo(() => {
    const set = /* @__PURE__ */ new Set();
    for (const variant of variants ?? []) {
      for (const opt of variant.options ?? []) {
        if (opt.option?.title) {
          set.add(opt.option.title);
        }
      }
    }
    return Array.from(set);
  }, [variants]);
  const filteredRows = useMemo(() => {
    let rows = allRows;
    const search = q?.trim().toLowerCase();
    if (search) {
      rows = rows.filter((row) => {
        const title = (row.variant.title ?? "").toLowerCase();
        return title.includes(search) || skuOf(row).toLowerCase().includes(search);
      });
    }
    const createdFilter = created_at ? JSON.parse(created_at) : null;
    if (createdFilter) {
      rows = rows.filter(
        (row) => matchesDateFilter(row.offer.created_at, createdFilter)
      );
    }
    const updatedFilter = updated_at ? JSON.parse(updated_at) : null;
    if (updatedFilter) {
      rows = rows.filter(
        (row) => matchesDateFilter(row.offer.updated_at, updatedFilter)
      );
    }
    return rows;
  }, [allRows, q, created_at, updated_at]);
  const sortedRows = useMemo(() => {
    const activeOrder = order || "title";
    const desc = activeOrder.startsWith("-");
    const key = desc ? activeOrder.slice(1) : activeOrder;
    const valueOf = (row) => {
      switch (key) {
        case "title":
          return row.variant.title ?? "";
        case "sku":
          return skuOf(row);
        case "created_at":
          return row.offer.created_at ? new Date(row.offer.created_at).toISOString() : "";
        case "updated_at":
          return row.offer.updated_at ? new Date(row.offer.updated_at).toISOString() : "";
        default:
          return "";
      }
    };
    const sorted = [...filteredRows].sort(
      (a, b) => valueOf(a).localeCompare(valueOf(b))
    );
    return desc ? sorted.reverse() : sorted;
  }, [filteredRows, order]);
  const pageIndex = offset ? Math.floor(parseInt(offset) / PAGE_SIZE) : 0;
  const pageRows = useMemo(
    () => sortedRows.slice(pageIndex * PAGE_SIZE, (pageIndex + 1) * PAGE_SIZE),
    [sortedRows, pageIndex]
  );
  const handleEdit = useCallback(
    (offerId) => navigate(`variants/${offerId}/edit`),
    [navigate]
  );
  const handleDelete = useCallback(
    async (offerId, sku) => {
      const confirmed = await prompt({
        title: t("general.areYouSure"),
        description: t("offers.delete.description", { sku: sku || "-" }),
        confirmText: t("actions.delete"),
        cancelText: t("actions.cancel"),
        variant: "danger"
      });
      if (!confirmed) {
        return;
      }
      const result = await bulkDelete([offerId]);
      if (result.failed.length === 0) {
        toast2.success(t("offers.delete.successToast"));
      } else {
        toast2.error(result.failed[0]?.error.message);
      }
    },
    [prompt, bulkDelete, t]
  );
  const columns = useColumns({
    optionTitles,
    thumbnail,
    onEdit: handleEdit,
    onDelete: handleDelete
  });
  const orderBy = useMemo(
    () => [
      { key: "title", label: t("fields.title") },
      { key: "sku", label: t("fields.sku") },
      { key: "created_at", label: t("fields.createdAt") },
      { key: "updated_at", label: t("fields.updatedAt") }
    ],
    [t]
  );
  const filters = useMemo(
    () => [
      { key: "created_at", label: t("fields.createdAt"), type: "date" },
      { key: "updated_at", label: t("fields.updatedAt"), type: "date" }
    ],
    [t]
  );
  const { table } = useDataTable({
    data: pageRows,
    columns,
    count: sortedRows.length,
    pageSize: PAGE_SIZE,
    getRowId: (row) => row.id,
    prefix: PREFIX
  });
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", "data-testid": "offer-variants-section", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx2(Heading2, { level: "h2", children: t("offers.fields.variants") }),
      /* @__PURE__ */ jsx2("div", { className: "flex items-center gap-x-4", children: /* @__PURE__ */ jsx2(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("offers.actions.edit_prices"),
                  icon: /* @__PURE__ */ jsx2(CurrencyDollar, {}),
                  to: "edit-price"
                },
                {
                  label: t("offers.actions.edit_stock_levels"),
                  icon: /* @__PURE__ */ jsx2(Buildings, {}),
                  to: "edit-stock"
                }
              ]
            }
          ]
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx2(
      _DataTable,
      {
        table,
        columns,
        count: sortedRows.length,
        pageSize: PAGE_SIZE,
        prefix: PREFIX,
        pagination: true,
        search: true,
        orderBy,
        defaultOrderBy: "title",
        filters,
        queryObject: { q, order, created_at, updated_at },
        navigateTo: (row) => `variants/${row.original.id}`,
        noRecords: {
          title: t("offers.empty.heading"),
          message: t("offers.empty.description")
        }
      }
    ),
    /* @__PURE__ */ jsx2(DisplayExtensionZone2, { model: "offer", zone: "variants", data: variants })
  ] });
};

// src/pages/offers/[id]/_components/offer-associated-product-section.tsx
import { TriangleRightMini } from "@medusajs/icons";
import { Container as Container3, Heading as Heading3 } from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";
import { Link } from "react-router-dom";
import { DisplayExtensionZone as DisplayExtensionZone3 } from "@mercurjs/dashboard-shared";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var OfferAssociatedProductSection = ({
  product
}) => {
  const { t } = useTranslation3();
  return /* @__PURE__ */ jsxs3(Container3, { className: "p-0", "data-testid": "offer-associated-product-section", children: [
    /* @__PURE__ */ jsx3("div", { className: "flex items-center justify-between px-6 py-4", children: /* @__PURE__ */ jsx3(Heading3, { level: "h2", children: t("offers.detail.associatedProduct") }) }),
    /* @__PURE__ */ jsx3("div", { className: "txt-small flex flex-col gap-2 px-2 pb-2", children: /* @__PURE__ */ jsx3(
      Link,
      {
        to: `/products/${product.id}`,
        className: "outline-none focus-within:shadow-borders-interactive-with-focus rounded-md [&:hover>div]:bg-ui-bg-component-hover",
        "data-testid": "offer-associated-product-link",
        children: /* @__PURE__ */ jsx3("div", { className: "shadow-elevation-card-rest bg-ui-bg-component rounded-md px-4 py-2 transition-colors", children: /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsx3("div", { className: "shadow-elevation-card-rest rounded-md", children: /* @__PURE__ */ jsx3(Thumbnail, { src: product.thumbnail ?? null }) }),
          /* @__PURE__ */ jsxs3("div", { className: "flex flex-1 flex-col overflow-hidden", children: [
            /* @__PURE__ */ jsx3("span", { className: "text-ui-fg-base truncate font-medium", children: product.title }),
            product.handle && /* @__PURE__ */ jsxs3("span", { className: "text-ui-fg-subtle truncate", children: [
              "/",
              product.handle
            ] })
          ] }),
          /* @__PURE__ */ jsx3("div", { className: "size-7 flex items-center justify-center", children: /* @__PURE__ */ jsx3(TriangleRightMini, { className: "text-ui-fg-muted rtl:rotate-180" }) })
        ] }) })
      }
    ) }),
    /* @__PURE__ */ jsx3(
      DisplayExtensionZone3,
      {
        model: "offer",
        zone: "associated-product",
        data: product
      }
    )
  ] });
};

// src/pages/offers/[id]/offer-detail-page.tsx
import { Fragment, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const { id } = useParams();
  const initialData = useLoaderData();
  const query = useLinkQuery("offer", OFFER_PRODUCT_DETAIL_FIELDS);
  const { product, isLoading, isError, error } = useProduct(id, query, {
    initialData
  });
  if (isError) {
    throw error;
  }
  if (isLoading || !product) {
    return /* @__PURE__ */ jsx4(TwoColumnPageSkeleton, { mainSections: 3, sidebarSections: 1 });
  }
  const typed = product;
  return /* @__PURE__ */ jsx4(Fragment, { children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs4(TwoColumnPage, { data: typed, hasOutlet: true, children: [
    /* @__PURE__ */ jsx4(TwoColumnPage.Main, { children: /* @__PURE__ */ jsxs4(WidgetZone, { id: "offers.detail.main", data: typed, children: [
      /* @__PURE__ */ jsx4(OfferDetailGeneralSection, { product: typed }),
      /* @__PURE__ */ jsx4(ProductMediaSection, { product: typed, readOnly: true }),
      /* @__PURE__ */ jsx4(
        OfferVariantsSection,
        {
          variants: typed.variants,
          thumbnail: typed.thumbnail
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx4(TwoColumnPage.Sidebar, { children: /* @__PURE__ */ jsx4(WidgetZone, { id: "offers.detail.side", data: typed, children: /* @__PURE__ */ jsx4(OfferAssociatedProductSection, { product: typed }) }) })
  ] }) });
};
var OfferDetailPage = Object.assign(Root, {
  Main: TwoColumnPage.Main,
  Sidebar: TwoColumnPage.Sidebar,
  General: OfferDetailGeneralSection,
  Media: ProductMediaSection,
  Variants: OfferVariantsSection,
  AssociatedProduct: OfferAssociatedProductSection
});
var Component2 = Root;
export {
  Component2 as Component,
  OfferDetailPage
};
