import {
  OFFER_PRODUCT_DETAIL_FIELDS
} from "./chunk-XQUF3WIS.js";
import {
  DataGrid,
  createDataGridHelper,
  createDataGridPriceColumns
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import {
  usePricePreferences
} from "./chunk-BHEU34FL.js";
import {
  useCurrentSeller
} from "./chunk-W34KDYZA.js";
import {
  offerQueryKeys
} from "./chunk-5DKUSZQ7.js";
import {
  productsQueryKeys,
  useProduct
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/offers/[id]/edit-price/index.tsx
import { Button, toast } from "@medusajs/ui";
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var numericOrZero = (v) => v === "" || v === null || v === void 0 ? 0 : Number(v) || 0;
var buildRows = (product, currencies) => (product.variants ?? []).flatMap(
  (variant) => (variant.offers ?? []).map((offer) => {
    const prices = {};
    for (const code of currencies) {
      const match = (offer.prices ?? []).find(
        (p) => p.currency_code === code
      );
      prices[code] = match?.amount ?? "";
    }
    return {
      offer_id: offer.id,
      variant_title: variant.title ?? "",
      product_thumbnail: product.thumbnail ?? null,
      prices
    };
  })
);
var columnHelper = createDataGridHelper();
var useColumns = ({
  currencies,
  pricePreferences
}) => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.column({
        id: "title",
        header: t("fields.title"),
        cell: (context) => {
          const entity = context.row.original;
          return /* @__PURE__ */ jsx(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full items-center gap-x-2 overflow-hidden", children: [
            /* @__PURE__ */ jsx(Thumbnail, { src: entity.product_thumbnail ?? null }),
            /* @__PURE__ */ jsx("span", { className: "truncate", title: entity.variant_title, children: entity.variant_title })
          ] }) });
        },
        disableHiding: true
      }),
      ...createDataGridPriceColumns({
        currencies,
        pricePreferences: pricePreferences ?? [],
        getFieldName: (context, value) => {
          if (context.column.id?.startsWith("currency_prices")) {
            return `rows.${context.row.index}.prices.${value}`;
          }
          return null;
        },
        t
      })
    ],
    [t, currencies, pricePreferences]
  );
};
var EditPriceGrid = ({
  product,
  productId
}) => {
  const { t } = useTranslation();
  const { handleSuccess, setCloseOnEscape } = useRouteModal();
  const { currency_code } = useCurrentSeller();
  const { price_preferences: pricePreferences } = usePricePreferences({});
  const currencies = useMemo(
    () => currency_code ? [currency_code] : [],
    [currency_code]
  );
  const rows = useMemo(
    () => buildRows(product, currencies),
    [product, currencies]
  );
  const form = useForm({ defaultValues: { rows } });
  const columns = useColumns({ currencies, pricePreferences });
  const handleSubmit = form.handleSubmit(async (values) => {
    try {
      await Promise.all(
        values.rows.map((row) => {
          const prices = currencies.map((code) => ({
            amount: numericOrZero(row.prices?.[code]),
            currency_code: code
          }));
          return sdk.vendor.offers.$id.mutate({ $id: row.offer_id, prices });
        })
      );
      await queryClient.invalidateQueries({ queryKey: offerQueryKeys.lists() });
      await queryClient.invalidateQueries({
        queryKey: productsQueryKeys.detail(productId)
      });
      toast.success(t("offers.pricing.successToast"));
      handleSuccess();
    } catch (error) {
      toast.error(error.message);
    }
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      "data-testid": "offer-edit-price-form",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex-1 overflow-hidden p-0", children: /* @__PURE__ */ jsx(
          DataGrid,
          {
            columns,
            data: rows,
            state: form,
            onEditingChange: (editing) => setCloseOnEscape(!editing)
          }
        ) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: form.formState.isSubmitting,
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};
var OfferEditPricePage = () => {
  const { id } = useParams();
  const { t } = useTranslation();
  const { product, isPending, isError, error } = useProduct(id, {
    fields: OFFER_PRODUCT_DETAIL_FIELDS
  });
  if (isError) throw error;
  return /* @__PURE__ */ jsxs(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("offers.pricing.header") }) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("offers.pricing.description") }) }),
    !isPending && product && /* @__PURE__ */ jsx(EditPriceGrid, { product, productId: id })
  ] });
};
var Component = OfferEditPricePage;
export {
  Component,
  OfferEditPricePage
};
