import {
  ConditionalPriceForm,
  ConditionalPriceSchema,
  ShippingOptionPriceProvider,
  useShippingOptionPriceColumns
} from "./chunk-YXWZT3PX.js";
import {
  CONDITIONAL_PRICES_STACKED_MODAL_ID,
  ShippingOptionPriceType
} from "./chunk-BCU3FKP2.js";
import "./chunk-XCHKUSUU.js";
import {
  DataGrid
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import {
  useComboboxData
} from "./chunk-OVPAOBZB.js";
import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import {
  Combobox
} from "./chunk-VBRTC2VU.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./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 {
  shippingProfileQueryKeys
} from "./chunk-EPSDO2MJ.js";
import "./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 {
  useCreateShippingOptions
} from "./chunk-VWPNMEOE.js";
import {
  useFulfillmentProviderOptions,
  useStockLocation
} from "./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 {
  fetchQuery
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/index.tsx
import { useParams, useSearchParams } from "react-router-dom";

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, ProgressTabs, toast } from "@medusajs/ui";
import { useForm, useWatch as useWatch2 } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useState as useState2 } from "react";

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-option-details-form.tsx
import { Heading, Input, RadioGroup, Text } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var CreateShippingOptionDetailsForm = ({
  form,
  isReturn = false,
  zone,
  type
}) => {
  const { t } = useTranslation();
  const isPickup = type === "pickup" /* Pickup */;
  const shippingProfiles = useComboboxData({
    queryFn: () => fetchQuery(`/vendor/shipping-profiles`, {
      method: "GET"
    }),
    queryKey: shippingProfileQueryKeys.lists(),
    getOptions: (data) => (data.shipping_profiles || []).map((profile) => {
      const name = profile.shipping_profile?.name ?? profile.name ?? "";
      const id = profile.shipping_profile?.id ?? profile.id;
      return {
        label: name.includes(":") ? name.split(":")[1] : name,
        value: id
      };
    })
  });
  return /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 px-6 py-16", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(Heading, { children: t(
        `stockLocations.shippingOptions.create.${isPickup ? "pickup" : isReturn ? "returns" : "shipping"}.header`,
        {
          zone: zone.name
        }
      ) }),
      /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t(
        `stockLocations.shippingOptions.create.${isReturn ? "returns" : isPickup ? "pickup" : "shipping"}.hint`
      ) })
    ] }),
    !isPickup && /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "price_type",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { children: [
            /* @__PURE__ */ jsx(Form.Label, { children: t("stockLocations.shippingOptions.fields.priceType.label") }),
            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                className: "grid grid-cols-1 gap-4 md:grid-cols-2",
                ...field,
                onValueChange: field.onChange,
                children: [
                  /* @__PURE__ */ jsx(
                    RadioGroup.ChoiceBox,
                    {
                      className: "flex-1",
                      value: "flat" /* FlatRate */,
                      label: t(
                        "stockLocations.shippingOptions.fields.priceType.options.fixed.label"
                      ),
                      description: t(
                        "stockLocations.shippingOptions.fields.priceType.options.fixed.hint"
                      )
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    RadioGroup.ChoiceBox,
                    {
                      className: "flex-1",
                      value: "calculated" /* Calculated */,
                      label: t(
                        "stockLocations.shippingOptions.fields.priceType.options.calculated.label"
                      ),
                      description: t(
                        "stockLocations.shippingOptions.fields.priceType.options.calculated.hint"
                      )
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, {})
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "name",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("fields.name") }),
              /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, {})
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "shipping_profile_id",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("stockLocations.shippingOptions.fields.profile") }),
              /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                Combobox,
                {
                  ...field,
                  options: shippingProfiles.options,
                  searchValue: shippingProfiles.searchValue,
                  onSearchValueChange: shippingProfiles.onSearchValueChange,
                  disabled: shippingProfiles.disabled
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, {})
            ] });
          }
        }
      )
    ] })
  ] }) });
};

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-prices-form.tsx
import { useEffect, useMemo, useState } from "react";
import { useWatch } from "react-hook-form";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CreateShippingOptionsPricesForm = ({
  form,
  type
}) => {
  const isPickup = type === "pickup" /* Pickup */;
  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 {
    currency_code,
    isPending: isSellerLoading,
    isError: isSellerError,
    error: sellerError
  } = useCurrentSeller();
  const currencies = useMemo(
    () => currency_code ? [currency_code] : [],
    [currency_code]
  );
  const {
    regions,
    isLoading: isRegionsLoading,
    isError: isRegionsError,
    error: regionsError
  } = useRegions({
    fields: "id,name,currency_code",
    limit: 999
  });
  const { setCloseOnEscape } = useRouteModal();
  const name = useWatch({
    control: form.control,
    name: "name"
  });
  const columns = useShippingOptionPriceColumns({
    name,
    currencies,
    regions
  });
  const isLoading = isSellerLoading || !currency_code || isRegionsLoading || !regions;
  const data = useMemo(
    () => [[...currencies || [], ...regions || []]],
    [currencies, regions]
  );
  useEffect(() => {
    if (!isLoading && isPickup) {
      if (currencies.length > 0) {
        currencies.forEach((currency) => {
          form.setValue(`currency_prices.${currency}`, "0");
        });
      }
      if (regions.length > 0) {
        regions.forEach((region) => {
          form.setValue(`region_prices.${region.id}`, "0");
        });
      }
    }
  }, [
    isLoading,
    isPickup,
    currencies.length,
    currencies,
    regions?.length,
    regions,
    form
  ]);
  if (isSellerError) {
    throw sellerError;
  }
  if (isRegionsError) {
    throw regionsError;
  }
  return /* @__PURE__ */ jsx2(
    StackedFocusModal,
    {
      id: CONDITIONAL_PRICES_STACKED_MODAL_ID,
      onOpenChangeCallback: (open) => {
        if (!open) {
          setSelectedPrice(null);
        }
      },
      children: /* @__PURE__ */ jsx2(
        ShippingOptionPriceProvider,
        {
          onOpenConditionalPricesModal,
          onCloseConditionalPricesModal,
          children: /* @__PURE__ */ jsxs2("div", { className: "flex size-full flex-col divide-y overflow-hidden", children: [
            /* @__PURE__ */ jsx2(
              DataGrid,
              {
                isLoading,
                data,
                columns,
                state: form,
                onEditingChange: (editing) => setCloseOnEscape(!editing),
                disableInteractions: getIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID)
              }
            ),
            selectedPrice && /* @__PURE__ */ jsx2(ConditionalPriceForm, { info: selectedPrice, variant: "create" })
          ] })
        }
      )
    }
  );
};

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/schema.ts
import { z } from "zod";
var CreateShippingOptionDetailsSchema = z.object({
  name: z.string().min(1),
  price_type: z.nativeEnum(ShippingOptionPriceType),
  enabled_in_store: z.boolean(),
  shipping_profile_id: z.string().min(1),
  provider_id: z.string().min(1),
  fulfillment_option_id: z.string().optional()
});
var ShippingOptionConditionalPriceSchema = z.object({
  conditional_region_prices: z.record(
    z.string(),
    z.array(ConditionalPriceSchema).optional()
  ),
  conditional_currency_prices: z.record(
    z.string(),
    z.array(ConditionalPriceSchema).optional()
  )
});
var CreateShippingOptionSchema = z.object({
  region_prices: z.record(z.string(), z.string().optional()),
  currency_prices: z.record(z.string(), z.string().optional())
}).merge(CreateShippingOptionDetailsSchema).merge(ShippingOptionConditionalPriceSchema);

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-form.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
function CreateShippingOptionsForm({
  zone,
  isReturn,
  locationId,
  type
}) {
  const [activeTab, setActiveTab] = useState2("details" /* DETAILS */);
  const [validDetails, setValidDetails] = useState2(false);
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      name: "",
      price_type: "flat" /* FlatRate */,
      enabled_in_store: true,
      shipping_profile_id: "",
      provider_id: "manual_manual",
      fulfillment_option_id: "",
      region_prices: {},
      currency_prices: {},
      conditional_region_prices: {},
      conditional_currency_prices: {}
    },
    resolver: zodResolver(CreateShippingOptionSchema)
  });
  const selectedProviderId = useWatch2({
    control: form.control,
    name: "provider_id"
  });
  const { fulfillment_options: fulfillmentProviderOptions } = useFulfillmentProviderOptions(selectedProviderId, {
    enabled: !!selectedProviderId
  });
  const isCalculatedPriceType = form.watch("price_type") === "calculated" /* Calculated */;
  const { mutateAsync, isPending: isLoading } = useCreateShippingOptions();
  const handleSubmit = form.handleSubmit(async (data) => {
    const currencyPrices = Object.entries(data.currency_prices).map(([code, value]) => {
      if (!value) {
        return void 0;
      }
      return {
        currency_code: code,
        amount: castNumber(value)
      };
    }).filter((p) => !!p);
    const regionPrices = Object.entries(data.region_prices).map(([region, value]) => {
      if (!value) {
        return void 0;
      }
      return {
        region_id: region,
        amount: castNumber(value)
      };
    }).filter((p) => !!p);
    const fulfillmentOptionData = fulfillmentProviderOptions?.find(
      (fo) => fo.id === data.fulfillment_option_id
    );
    await mutateAsync(
      {
        name: data.name,
        service_zone_id: zone.id,
        shipping_profile_id: data.shipping_profile_id,
        provider_id: data.provider_id,
        price_type: data.price_type,
        prices: [...currencyPrices, ...regionPrices],
        data: fulfillmentOptionData,
        rules: [
          {
            value: isReturn ? "true" : "false",
            attribute: "is_return",
            operator: "eq"
          },
          {
            value: "true",
            attribute: "enabled_in_store",
            operator: "eq"
          }
        ],
        type: {
          // TODO: FETCH TYPES
          label: "Type label",
          description: "Type description",
          code: "type-code"
        }
      },
      {
        onSuccess: ({ shipping_option }) => {
          toast.success(
            t(
              `stockLocations.shippingOptions.create.${isReturn ? "returns" : "shipping"}.successToast`,
              { name: shipping_option?.name }
            )
          );
          handleSuccess(`/settings/locations/${locationId}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  const onTabChange = (tab) => {
    if (tab === "pricing" /* PRICING */) {
      form.clearErrors();
      const result = CreateShippingOptionDetailsSchema.safeParse({
        ...form.getValues()
      });
      if (!result.success) {
        const [firstError, ...rest] = result.error.errors;
        for (const error of rest) {
          const _path = error.path.join(".");
          form.setError(_path, {
            message: error.message,
            type: error.code
          });
        }
        form.setError(
          firstError.path.join("."),
          {
            message: firstError.message,
            type: firstError.code
          },
          {
            shouldFocus: true
          }
        );
        setValidDetails(false);
        return;
      }
      setValidDetails(true);
    }
    setActiveTab(tab);
  };
  const pricesStatus = form.getFieldState("currency_prices")?.isDirty || form.getFieldState("region_prices")?.isDirty || activeTab === "pricing" /* PRICING */ ? "in-progress" : "not-started";
  const detailsStatus = validDetails ? "completed" : "in-progress";
  return /* @__PURE__ */ jsx3(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsx3(
    KeyboundForm,
    {
      className: "flex h-full flex-col",
      onSubmit: handleSubmit,
      onKeyDown: (e) => {
        const isEnterKey = e.key === "Enter";
        const isModifierPressed = e.metaKey || e.ctrlKey;
        const shouldContinueToPricing = activeTab !== "pricing" /* PRICING */ && !isCalculatedPriceType;
        if (!isEnterKey) {
          return;
        }
        e.preventDefault();
        if (!isModifierPressed) {
          return;
        }
        if (shouldContinueToPricing) {
          e.stopPropagation();
          onTabChange("pricing" /* PRICING */);
          return;
        }
        handleSubmit();
      },
      children: /* @__PURE__ */ jsxs3(
        ProgressTabs,
        {
          value: activeTab,
          className: "flex h-full flex-col overflow-hidden",
          onValueChange: (tab) => onTabChange(tab),
          children: [
            /* @__PURE__ */ jsx3(RouteFocusModal.Header, { children: /* @__PURE__ */ jsxs3(ProgressTabs.List, { className: "border-ui-border-base -my-2 ml-2 min-w-0 flex-1 border-l", children: [
              /* @__PURE__ */ jsx3(
                ProgressTabs.Trigger,
                {
                  value: "details" /* DETAILS */,
                  status: detailsStatus,
                  className: "w-full max-w-[200px]",
                  children: /* @__PURE__ */ jsx3("span", { className: "w-full cursor-auto overflow-hidden text-ellipsis whitespace-nowrap", children: t("stockLocations.shippingOptions.create.tabs.details") })
                }
              ),
              !isCalculatedPriceType && /* @__PURE__ */ jsx3(
                ProgressTabs.Trigger,
                {
                  value: "pricing" /* PRICING */,
                  status: pricesStatus,
                  className: "w-full max-w-[200px]",
                  children: /* @__PURE__ */ jsx3("span", { className: "w-full overflow-hidden text-ellipsis whitespace-nowrap", children: t("stockLocations.shippingOptions.create.tabs.prices") })
                }
              )
            ] }) }),
            /* @__PURE__ */ jsxs3(RouteFocusModal.Body, { className: "size-full overflow-hidden", children: [
              /* @__PURE__ */ jsx3(
                ProgressTabs.Content,
                {
                  value: "details" /* DETAILS */,
                  className: "size-full overflow-y-auto",
                  children: /* @__PURE__ */ jsx3(
                    CreateShippingOptionDetailsForm,
                    {
                      form,
                      zone,
                      isReturn,
                      type
                    }
                  )
                }
              ),
              /* @__PURE__ */ jsx3(ProgressTabs.Content, { value: "pricing" /* PRICING */, className: "size-full", children: /* @__PURE__ */ jsx3(CreateShippingOptionsPricesForm, { form, type }) })
            ] }),
            /* @__PURE__ */ jsx3(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-end gap-x-2", children: [
              /* @__PURE__ */ jsx3(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
              activeTab === "pricing" /* PRICING */ || isCalculatedPriceType ? /* @__PURE__ */ jsx3(
                Button,
                {
                  size: "small",
                  className: "whitespace-nowrap",
                  isLoading,
                  type: "submit",
                  children: t("actions.save")
                },
                "submit-btn"
              ) : /* @__PURE__ */ jsx3(
                Button,
                {
                  size: "small",
                  className: "whitespace-nowrap",
                  isLoading,
                  onClick: () => onTabChange("pricing" /* PRICING */),
                  type: "button",
                  children: t("actions.continue")
                },
                "continue-btn"
              )
            ] }) })
          ]
        }
      )
    }
  ) });
}

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/constants.ts
var LOC_CREATE_SHIPPING_OPTION_FIELDS = "*fulfillment_sets,*fulfillment_sets.service_zones,*fulfillment_sets.service_zones.shipping_options";

// src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/index.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
function LocationServiceZoneShippingOptionCreate() {
  const { location_id, fset_id, zone_id } = useParams();
  const [searchParams] = useSearchParams();
  const isReturn = searchParams.has("is_return");
  const { stock_location, isPending, isFetching, isError, error } = useStockLocation(location_id, {
    fields: LOC_CREATE_SHIPPING_OPTION_FIELDS
  });
  const fulfillmentSet = stock_location?.fulfillment_sets?.find(
    (f) => f.id === fset_id
  );
  if (!isPending && !isFetching && !fulfillmentSet) {
    throw new Response(
      JSON.stringify({
        message: `Fulfillment set with ID ${fset_id} was not found`
      }),
      { status: 404, headers: { "Content-Type": "application/json" } }
    );
  }
  const zone = fulfillmentSet?.service_zones?.find((z2) => z2.id === zone_id);
  if (!isPending && !isFetching && !zone) {
    throw new Response(
      JSON.stringify({
        message: `Service zone with ID ${zone_id} was not found`
      }),
      { status: 404, headers: { "Content-Type": "application/json" } }
    );
  }
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx4(RouteFocusModal, { prev: `/settings/locations/${location_id}`, children: zone && /* @__PURE__ */ jsx4(
    CreateShippingOptionsForm,
    {
      zone,
      isReturn,
      locationId: location_id,
      type: fulfillmentSet.type
    }
  ) });
}
var Component = LocationServiceZoneShippingOptionCreate;
export {
  Component
};
