import {
  ConditionalPriceForm,
  ShippingOptionPriceProvider,
  UpdateConditionalPriceSchema,
  useShippingOptionPriceColumns
} from "./chunk-YXWZT3PX.js";
import {
  CONDITIONAL_PRICES_STACKED_MODAL_ID,
  ITEM_TOTAL_ATTRIBUTE,
  REGION_ID_ATTRIBUTE
} from "./chunk-BCU3FKP2.js";
import "./chunk-XCHKUSUU.js";
import {
  DataGrid
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} 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 {
  useRegions
} from "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import {
  usePricePreferences
} from "./chunk-BHEU34FL.js";
import {
  useCurrentSeller
} from "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import {
  useShippingOption,
  useUpdateShippingOptions
} from "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.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/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/index.tsx
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/_components/edit-shipping-options-pricing-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import * as zod from "zod";
import { Button, toast } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var EditShippingOptionPricingSchema = zod.object({
  region_prices: zod.record(
    zod.string(),
    zod.string().or(zod.number()).optional()
  ),
  currency_prices: zod.record(
    zod.string(),
    zod.string().or(zod.number()).optional()
  ),
  conditional_region_prices: zod.record(
    zod.string(),
    zod.array(UpdateConditionalPriceSchema)
  ),
  conditional_currency_prices: zod.record(
    zod.string(),
    zod.array(UpdateConditionalPriceSchema)
  )
});
function EditShippingOptionsPricingForm({
  shippingOption
}) {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { getIsOpen, setIsOpen } = useStackedModal();
  const [selectedPrice, setSelectedPrice] = useState(null);
  const onOpenConditionalPricesModal = (info) => {
    setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, true);
    setSelectedPrice(info);
  };
  const onCloseConditionalPricesModal = () => {
    setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, false);
    setSelectedPrice(null);
  };
  const form = useForm({
    defaultValues: getDefaultValues(shippingOption.prices),
    resolver: zodResolver(EditShippingOptionPricingSchema)
  });
  const { mutateAsync, isPending } = useUpdateShippingOptions(shippingOption.id);
  const {
    currency_code,
    isPending: isSellerLoading,
    isError: isSellerError,
    error: sellerError
  } = useCurrentSeller();
  const currencies = useMemo(
    () => currency_code ? [currency_code] : [],
    [currency_code]
  );
  const { price_preferences: pricePreferences } = usePricePreferences({});
  const { regions } = useRegions({
    fields: "id,name,currency_code",
    limit: 999
  });
  const { setCloseOnEscape } = useRouteModal();
  const columns = useShippingOptionPriceColumns({
    name: shippingOption.name,
    currencies,
    regions,
    pricePreferences
  });
  const data = useMemo(() => [[...currencies || []]], [currencies]);
  const handleSubmit = form.handleSubmit(async (data2) => {
    const regionPrices = Object.entries(data2.region_prices).map(([region_id, value]) => {
      const priceRecord = {
        region_id,
        amount: castNumber(value || 0)
        // currency_code: regions?.find((r) => r.id === region_id)
        //   ?.currency_code,
      };
      return priceRecord;
    }).filter((p) => !!p);
    const allPrices = [
      // ...currencyPrices,
      // ...conditionalCurrencyPrices,
      ...regionPrices
      // ...conditionalRegionPrices,
    ];
    await mutateAsync(
      { prices: allPrices },
      {
        onSuccess: () => {
          toast.success(t("general.success"));
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  const isLoading = isSellerLoading || currencies.length === 0;
  if (isSellerError) {
    throw sellerError;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex h-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { children: /* @__PURE__ */ jsx(
          StackedFocusModal,
          {
            id: CONDITIONAL_PRICES_STACKED_MODAL_ID,
            onOpenChangeCallback: (open) => {
              if (!open) {
                setSelectedPrice(null);
              }
            },
            children: /* @__PURE__ */ jsxs(
              ShippingOptionPriceProvider,
              {
                onOpenConditionalPricesModal,
                onCloseConditionalPricesModal,
                children: [
                  /* @__PURE__ */ jsx("div", { className: "flex size-full flex-col divide-y overflow-hidden", children: /* @__PURE__ */ jsx(
                    DataGrid,
                    {
                      isLoading,
                      data,
                      columns,
                      state: form,
                      onEditingChange: (editing) => setCloseOnEscape(!editing),
                      disableInteractions: getIsOpen(
                        CONDITIONAL_PRICES_STACKED_MODAL_ID
                      )
                    }
                  ) }),
                  selectedPrice && /* @__PURE__ */ jsx(ConditionalPriceForm, { info: selectedPrice, variant: "update" })
                ]
              }
            )
          }
        ) }),
        /* @__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", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              className: "whitespace-nowrap",
              isLoading: isPending,
              onClick: handleSubmit,
              type: "button",
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
}
var findRuleValue = (rules, operator) => {
  const fallbackValue = ["eq", "gt", "lt"].includes(operator) ? void 0 : null;
  return rules?.find(
    (r) => r.attribute === ITEM_TOTAL_ATTRIBUTE && r.operator === operator
  )?.value || fallbackValue;
};
var mapToConditionalPrice = (price) => {
  const rules = price.price_rules || [];
  return {
    id: price.id,
    amount: price.amount,
    gte: findRuleValue(rules, "gte"),
    lte: findRuleValue(rules, "lte"),
    gt: findRuleValue(rules, "gt"),
    lt: findRuleValue(rules, "lt"),
    eq: findRuleValue(rules, "eq")
  };
};
var getDefaultValues = (prices) => {
  const hasAttributes = (price, required, forbidden = []) => {
    const attributes = price.price_rules?.map((r) => r.attribute) || [];
    return required.every((attr) => attributes.includes(attr)) && !forbidden.some((attr) => attributes.includes(attr));
  };
  const currency_prices = {};
  const conditional_currency_prices = {};
  const region_prices = {};
  const conditional_region_prices = {};
  prices.forEach((price) => {
    if (!price.price_rules?.length) {
      currency_prices[price.currency_code] = price.amount;
      return;
    }
    const region_id = price.price_rules?.find(
      (r) => r.attribute === REGION_ID_ATTRIBUTE
    )?.value;
    if (region_id) {
      region_prices[region_id] = price.amount;
      return;
    }
    if (hasAttributes(price, [ITEM_TOTAL_ATTRIBUTE], [REGION_ID_ATTRIBUTE])) {
      const code = price.currency_code;
      if (!conditional_currency_prices[code]) {
        conditional_currency_prices[code] = [];
      }
      conditional_currency_prices[code].push(mapToConditionalPrice(price));
      return;
    }
  });
  return {
    currency_prices,
    conditional_currency_prices,
    region_prices,
    conditional_region_prices
  };
};

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/index.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
function LocationServiceZoneShippingOptionPricing() {
  const { t } = useTranslation2();
  const { so_id, location_id } = useParams();
  if (!so_id) {
    throw new Response(
      JSON.stringify({ message: t("validation.shippingOptionIdMissing") }),
      { status: 404, headers: { "Content-Type": "application/json" } }
    );
  }
  const {
    shipping_option: shippingOption,
    isError,
    error
  } = useShippingOption(so_id, {
    fields: "*prices,*prices.price_rules"
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { prev: `/settings/locations/${location_id}`, children: shippingOption && /* @__PURE__ */ jsx2(EditShippingOptionsPricingForm, { shippingOption }) });
}
var Component = LocationServiceZoneShippingOptionPricing;
export {
  Component
};
