import {
  DataGrid,
  createDataGridHelper,
  createDataGridPriceColumns
} from "./chunk-U3OWJE7V.js";
import "./chunk-IQPN4PZJ.js";
import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import {
  useRegions
} from "./chunk-W5UPPL3W.js";
import {
  useStore
} from "./chunk-LC6TM5OT.js";
import {
  usePricePreferences
} from "./chunk-7SJC6BWZ.js";
import {
  useProduct,
  useUpdateProductVariantsBatch
} from "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/products/product-prices/product-prices.tsx
import { useParams } from "react-router-dom";

// src/pages/products/product-prices/pricing-edit.tsx
import { useMemo as useMemo2 } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import * as zod from "zod";

// src/pages/products/common/variant-pricing-form.tsx
import { useMemo } from "react";
import { useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { jsx } from "react/jsx-runtime";
var VariantPricingForm = ({
  form,
  "data-testid": dataTestId
}) => {
  const { store } = useStore();
  const { regions } = useRegions({ limit: 9999 });
  const { price_preferences: pricePreferences } = usePricePreferences({});
  const { setCloseOnEscape } = useRouteModal();
  const columns = useVariantPriceGridColumns({
    currencies: store?.supported_currencies,
    regions,
    pricePreferences
  });
  const variants = useWatch({
    control: form.control,
    name: "variants"
  });
  return /* @__PURE__ */ jsx("div", { "data-testid": dataTestId, children: /* @__PURE__ */ jsx(
    DataGrid,
    {
      columns,
      data: variants,
      state: form,
      onEditingChange: (editing) => setCloseOnEscape(!editing),
      "data-testid": dataTestId
    }
  ) });
};
var columnHelper = createDataGridHelper();
var useVariantPriceGridColumns = ({
  currencies = [],
  regions = [],
  pricePreferences = []
}) => {
  const { t } = useTranslation();
  return useMemo(() => {
    return [
      columnHelper.column({
        id: t("fields.title"),
        header: t("fields.title"),
        cell: (context) => {
          const entity = context.row.original;
          return /* @__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: entity.title }) }) });
        },
        disableHiding: true
      }),
      ...createDataGridPriceColumns({
        currencies: currencies.map((c) => c.currency_code),
        regions,
        pricePreferences,
        getFieldName: (context, value) => {
          if (context.column.id?.startsWith("currency_prices")) {
            return `variants.${context.row.index}.prices.${value}`;
          }
          return `variants.${context.row.index}.prices.${value}`;
        },
        t
      })
    ];
  }, [t, currencies, regions, pricePreferences]);
};

// src/pages/products/product-prices/pricing-edit.tsx
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var UpdateVariantPricesSchema = zod.object({
  variants: zod.array(
    zod.object({
      prices: zod.record(zod.string(), zod.string().or(zod.number()).optional()).optional()
    })
  )
});
var PricingEdit = ({
  product,
  variantId
}) => {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const { mutateAsync, isPending } = useUpdateProductVariantsBatch(product.id);
  const { regions } = useRegions({ limit: 9999 });
  const regionsCurrencyMap = useMemo2(() => {
    if (!regions?.length) {
      return {};
    }
    return regions.reduce((acc, reg) => {
      acc[reg.id] = reg.currency_code;
      return acc;
    }, {});
  }, [regions]);
  const variants = variantId ? product.variants?.filter((v) => v.id === variantId) : product.variants;
  const form = useForm({
    defaultValues: {
      variants: variants?.map((variant) => ({
        title: variant.title,
        prices: variant.prices.reduce((acc, price) => {
          if (price.rules?.region_id) {
            acc[price.rules.region_id] = price.amount;
          } else {
            acc[price.currency_code] = price.amount;
          }
          return acc;
        }, {})
      }))
    },
    resolver: zodResolver(UpdateVariantPricesSchema, {})
  });
  const handleSubmit = form.handleSubmit(async (values) => {
    const reqData = values.variants.map((variant, ind) => ({
      id: variants[ind].id,
      prices: Object.entries(variant.prices || {}).filter(
        ([_, value]) => value !== "" && typeof value !== "undefined"
        // deleted cells
      ).map(([currencyCodeOrRegionId, value]) => {
        const regionId = currencyCodeOrRegionId.startsWith("reg_") ? currencyCodeOrRegionId : void 0;
        const currencyCode = currencyCodeOrRegionId.startsWith("reg_") ? regionsCurrencyMap[regionId] : currencyCodeOrRegionId;
        let existingId = void 0;
        if (regionId) {
          existingId = variants?.[ind]?.prices?.find((p) => p.rules["region_id"] === regionId)?.id;
        } else {
          existingId = variants?.[ind]?.prices?.find(
            (p) => p.currency_code === currencyCode && Object.keys(p.rules ?? {}).length === 0
          )?.id;
        }
        const amount = castNumber(value);
        return {
          id: existingId,
          currency_code: currencyCode,
          amount,
          ...regionId ? { rules: { region_id: regionId } } : {}
        };
      })
    }));
    await mutateAsync(reqData, {
      onSuccess: () => {
        handleSuccess("..");
      }
    });
  });
  return /* @__PURE__ */ jsx2(
    RouteFocusModal.Form,
    {
      form,
      "data-testid": "product-prices-form",
      children: /* @__PURE__ */ jsxs(
        KeyboundForm,
        {
          onSubmit: handleSubmit,
          className: "flex size-full flex-col",
          children: [
            /* @__PURE__ */ jsx2(RouteFocusModal.Header, { "data-testid": "product-prices-form-header" }),
            /* @__PURE__ */ jsx2(
              RouteFocusModal.Body,
              {
                className: "flex flex-col overflow-hidden",
                "data-testid": "product-prices-form-body",
                children: /* @__PURE__ */ jsx2("div", { "data-testid": "product-prices-form-variant-pricing-wrapper", children: /* @__PURE__ */ jsx2(
                  VariantPricingForm,
                  {
                    form,
                    "data-testid": "product-prices-form-variant-pricing"
                  }
                ) })
              }
            ),
            /* @__PURE__ */ jsx2(RouteFocusModal.Footer, { "data-testid": "product-prices-form-footer", children: /* @__PURE__ */ jsxs(
              "div",
              {
                className: "flex w-full items-center justify-end gap-x-2",
                "data-testid": "product-prices-form-footer-actions",
                children: [
                  /* @__PURE__ */ jsx2(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx2(
                    Button,
                    {
                      variant: "secondary",
                      size: "small",
                      "data-testid": "product-prices-form-cancel-button",
                      children: t("actions.cancel")
                    }
                  ) }),
                  /* @__PURE__ */ jsx2(
                    Button,
                    {
                      type: "submit",
                      variant: "primary",
                      size: "small",
                      isLoading: isPending,
                      "data-testid": "product-prices-form-save-button",
                      children: t("actions.save")
                    }
                  )
                ]
              }
            ) })
          ]
        }
      )
    }
  );
};

// src/pages/products/product-prices/product-prices.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var ProductPrices = () => {
  const { id, variant_id } = useParams();
  const { product, isLoading, isError, error } = useProduct(id);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx3(RouteFocusModal, { "data-testid": "product-prices-modal", children: !isLoading && product && /* @__PURE__ */ jsx3(PricingEdit, { product, variantId: variant_id }) });
};
export {
  ProductPrices as Component
};
