import {
  OFFER_VARIANT_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 "./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 {
  useOffer,
  useUpdateOffer
} from "./chunk-5DKUSZQ7.js";
import "./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]/variants/[offer_id]/pricing/index.tsx
import { useParams } from "react-router-dom";

// src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, toast } from "@medusajs/ui";
import { useMemo } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";

// src/pages/offers/[id]/pricing/pricing-form/schema.ts
import { z } from "zod";
var PriceCellSchema = z.union([z.coerce.number().min(0), z.literal("")]);
var PriceRowSchema = z.object({
  id: z.string(),
  currency_prices: z.record(z.string(), PriceCellSchema).default({})
});
var PricingFormSchema = z.object({
  prices: z.array(PriceRowSchema).min(1)
});

// src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var isBaseRow = (price) => {
  const rules = price.price_rules ?? [];
  const extraRules = rules.filter((r) => r.attribute !== "offer_id");
  return extraRules.length === 0;
};
var buildDefaults = (offer, currencies) => {
  const basePrice = {
    id: offer.id,
    currency_prices: currencies.reduce(
      (acc, code) => {
        const existing = offer.prices?.find(
          (p) => isBaseRow(p) && p.currency_code === code
        );
        acc[code] = existing?.amount ?? "";
        return acc;
      },
      {}
    )
  };
  return { prices: [basePrice] };
};
var PricingForm = ({ offer }) => {
  const { currency_code, isPending: isSellerPending } = useCurrentSeller();
  const currencies = useMemo(
    () => currency_code ? [currency_code] : [],
    [currency_code]
  );
  if (isSellerPending || !currencies.length) return null;
  return /* @__PURE__ */ jsx(PricingFormInner, { offer, currencies });
};
var PricingFormInner = ({
  offer,
  currencies
}) => {
  const { t } = useTranslation();
  const { handleSuccess, setCloseOnEscape } = useRouteModal();
  const { price_preferences: pricePreferences } = usePricePreferences({});
  const defaults = useMemo(
    () => buildDefaults(offer, currencies),
    [offer, currencies]
  );
  const form = useForm({
    defaultValues: defaults,
    resolver: zodResolver(PricingFormSchema)
  });
  const columns = usePriceGridColumns({
    currencies,
    pricePreferences
  });
  const prices = useWatch({
    control: form.control,
    name: "prices",
    defaultValue: defaults.prices
  });
  const { mutateAsync, isPending } = useUpdateOffer(offer.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const row = values.prices[0];
    const submitted = [];
    for (const [currency_code, amount] of Object.entries(
      row.currency_prices ?? {}
    )) {
      if (amount === "" || amount === void 0 || amount === null) continue;
      const num = Number(amount);
      if (!Number.isFinite(num)) continue;
      submitted.push({ amount: num, currency_code });
    }
    await mutateAsync(
      { prices: submitted },
      {
        onSuccess: () => {
          toast.success(t("offers.pricing.successToast"));
          handleSuccess();
        },
        onError: (e) => toast.error(e.message)
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "offer-pricing-edit-form", children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex size-full flex-col", children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-col overflow-hidden", children: /* @__PURE__ */ jsx(
      DataGrid,
      {
        state: form,
        columns,
        data: prices,
        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, { variant: "secondary", size: "small", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(Button, { type: "submit", size: "small", isLoading: isPending, children: t("actions.save") })
    ] }) })
  ] }) });
};
var columnHelper = createDataGridHelper();
var usePriceGridColumns = ({
  currencies = [],
  pricePreferences = []
}) => {
  const { t } = useTranslation();
  return useMemo(() => {
    return [
      columnHelper.column({
        id: "title",
        name: t("fields.title"),
        header: t("fields.title"),
        cell: (context) => /* @__PURE__ */ jsx(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsx("div", { className: "flex h-full w-full items-center gap-x-2 overflow-hidden", children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t("labels.prices") }) }) }),
        disableHiding: true
      }),
      ...createDataGridPriceColumns({
        currencies,
        pricePreferences,
        getFieldName: (context, value) => {
          if (context.column.id?.startsWith("currency_prices")) {
            return `prices.${context.row.index}.currency_prices.${value}`;
          }
          return null;
        },
        t
      })
    ];
  }, [t, currencies, pricePreferences]);
};

// src/pages/offers/[id]/variants/[offer_id]/pricing/index.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var OfferVariantPricingPage = () => {
  const { offer_id } = useParams();
  const { offer, isPending, isError, error } = useOffer(offer_id, {
    fields: OFFER_VARIANT_DETAIL_FIELDS
  });
  if (isError) throw error;
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "offer-variant-pricing-modal", children: !isPending && offer && /* @__PURE__ */ jsx2(PricingForm, { offer }) });
};
var Component = OfferVariantPricingPage;
export {
  Component,
  OfferVariantPricingPage
};
