import {
  ShippingOptionPriceType
} from "./chunk-LXSBG6LK.js";
import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  isOptionEnabledInStore
} from "./chunk-HC25LNX7.js";
import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useShippingOptions,
  useUpdateShippingOptions
} from "./chunk-O4STPJR2.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/locations/location-service-zone-shipping-option-edit/location-service-zone-shipping-option-edit.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/locations/location-service-zone-shipping-option-edit/components/edit-region-form/edit-shipping-option-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Divider, Input, RadioGroup, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var EditShippingOptionSchema = zod.object({
  name: zod.string().min(1),
  price_type: zod.nativeEnum(ShippingOptionPriceType),
  enabled_in_store: zod.boolean().optional(),
  shipping_profile_id: zod.string(),
  shipping_option_type_id: zod.string(),
  provider_id: zod.string().optional()
  // just for UI purposes
});
var EditShippingOptionForm = ({
  locationId,
  shippingOption,
  type
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const direction = useDocumentDirection();
  const isPickup = type === "pickup" /* Pickup */;
  const shippingProfiles = useComboboxData({
    queryFn: (params) => sdk.admin.shippingProfiles.query(params),
    queryKey: ["shipping_profiles"],
    getOptions: (data) => data.shipping_profiles.map((profile) => ({
      label: profile.name,
      value: profile.id
    })),
    defaultValue: shippingOption.shipping_profile_id
  });
  const shippingOptionTypes = useComboboxData({
    queryFn: (params) => sdk.admin.shippingOptionTypes.query(params),
    queryKey: ["shipping_option_types"],
    getOptions: (data) => data.shipping_option_types.map((type2) => ({
      label: type2.label,
      value: type2.id
    }))
  });
  const form = useForm({
    defaultValues: {
      name: shippingOption.name,
      price_type: shippingOption.price_type,
      enabled_in_store: isOptionEnabledInStore(shippingOption),
      shipping_profile_id: shippingOption.shipping_profile_id,
      shipping_option_type_id: shippingOption.type.id,
      provider_id: shippingOption.provider_id
    },
    resolver: zodResolver(EditShippingOptionSchema)
  });
  const { mutateAsync, isPending: isLoading } = useUpdateShippingOptions(
    shippingOption.id
  );
  const handleSubmit = form.handleSubmit(async (values) => {
    const rules = shippingOption.rules.map((r) => ({
      id: r.id,
      attribute: r.attribute,
      operator: r.operator,
      value: r.value ?? ""
    }));
    const storeRule = rules.find((r) => r.attribute === "enabled_in_store");
    if (!storeRule) {
      rules.push({
        value: values.enabled_in_store ? "true" : "false",
        attribute: "enabled_in_store",
        operator: "eq"
      });
    } else {
      storeRule.value = values.enabled_in_store ? "true" : "false";
    }
    await mutateAsync(
      {
        name: values.name,
        price_type: values.price_type,
        shipping_profile_id: values.shipping_profile_id,
        rules,
        type_id: values.shipping_option_type_id
      },
      {
        onSuccess: ({ shipping_option }) => {
          toast.success(
            t("stockLocations.shippingOptions.edit.successToast", {
              name: shipping_option.name
            })
          );
          handleSuccess(`/settings/locations/${locationId}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "location-shipping-option-edit-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "overflow-y-auto", "data-testid": "location-shipping-option-edit-form-body", children: /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-8", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-8", children: [
          !isPickup && /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "price_type",
              render: ({ field }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "location-shipping-option-edit-form-price-type-item", children: [
                  /* @__PURE__ */ jsx(Form.Label, { "data-testid": "location-shipping-option-edit-form-price-type-label", children: t(
                    "stockLocations.shippingOptions.fields.priceType.label"
                  ) }),
                  /* @__PURE__ */ jsx(Form.Control, { "data-testid": "location-shipping-option-edit-form-price-type-control", children: /* @__PURE__ */ jsxs(
                    RadioGroup,
                    {
                      dir: direction,
                      ...field,
                      onValueChange: field.onChange,
                      "data-testid": "location-shipping-option-edit-form-price-type-radio-group",
                      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"
                            ),
                            "data-testid": "location-shipping-option-edit-form-price-type-flat-rate"
                          }
                        ),
                        /* @__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"
                            ),
                            "data-testid": "location-shipping-option-edit-form-price-type-calculated"
                          }
                        )
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "location-shipping-option-edit-form-price-type-error" })
                ] });
              }
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "grid gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "name",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "location-shipping-option-edit-form-name-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "location-shipping-option-edit-form-name-label", children: t("fields.name") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "location-shipping-option-edit-form-name-control", children: /* @__PURE__ */ jsx(Input, { ...field, "data-testid": "location-shipping-option-edit-form-name-input" }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "location-shipping-option-edit-form-name-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "shipping_profile_id",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "location-shipping-option-edit-form-shipping-profile-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "location-shipping-option-edit-form-shipping-profile-label", children: t("stockLocations.shippingOptions.fields.profile") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "location-shipping-option-edit-form-shipping-profile-control", children: /* @__PURE__ */ jsx(
                      Combobox,
                      {
                        ...field,
                        options: shippingProfiles.options,
                        searchValue: shippingProfiles.searchValue,
                        onSearchValueChange: shippingProfiles.onSearchValueChange,
                        disabled: shippingProfiles.disabled,
                        "data-testid": "location-shipping-option-edit-form-shipping-profile-combobox"
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "location-shipping-option-edit-form-shipping-profile-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "shipping_option_type_id",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "location-shipping-option-edit-form-shipping-option-type-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "location-shipping-option-edit-form-shipping-option-type-label", children: t("stockLocations.shippingOptions.fields.type") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "location-shipping-option-edit-form-shipping-option-type-control", children: /* @__PURE__ */ jsx(
                      Combobox,
                      {
                        ...field,
                        options: shippingOptionTypes.options,
                        searchValue: shippingOptionTypes.searchValue,
                        onSearchValueChange: shippingOptionTypes.onSearchValueChange,
                        disabled: shippingOptionTypes.disabled,
                        "data-testid": "location-shipping-option-edit-form-shipping-option-type-combobox"
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "location-shipping-option-edit-form-shipping-option-type-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "provider_id",
                disabled: true,
                render: () => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "location-shipping-option-edit-form-provider-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "location-shipping-option-edit-form-provider-label", children: t("stockLocations.shippingOptions.fields.provider") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "location-shipping-option-edit-form-provider-control", children: /* @__PURE__ */ jsx(
                      Combobox,
                      {
                        value: shippingOption.provider_id,
                        disabled: true,
                        options: [
                          {
                            label: `${formatProvider(
                              shippingOption.provider_id
                            )} (${shippingOption?.data?.id || "N/A"})`,
                            // FO is stored in so.data and only guaranteed proeprty is `id`
                            value: shippingOption.provider_id
                          }
                        ],
                        "data-testid": "location-shipping-option-edit-form-provider-combobox"
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "location-shipping-option-edit-form-provider-error" })
                  ] });
                }
              }
            )
          ] }),
          /* @__PURE__ */ jsx(Divider, {}),
          /* @__PURE__ */ jsx(
            SwitchBox,
            {
              control: form.control,
              name: "enabled_in_store",
              label: t(
                "stockLocations.shippingOptions.fields.enableInStore.label"
              ),
              description: t(
                "stockLocations.shippingOptions.fields.enableInStore.hint"
              ),
              "data-testid": "location-shipping-option-edit-form-enabled-in-store"
            }
          )
        ] }) }) }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { "data-testid": "location-shipping-option-edit-form-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", "data-testid": "location-shipping-option-edit-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading, "data-testid": "location-shipping-option-edit-form-save-button", children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/locations/location-service-zone-shipping-option-edit/location-service-zone-shipping-option-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var LocationServiceZoneShippingOptionEdit = () => {
  const { t } = useTranslation2();
  const { location_id, so_id } = useParams();
  const { shipping_options, isPending, isFetching, isError, error } = useShippingOptions({
    id: so_id,
    fields: "+service_zone.fulfillment_set.type"
  });
  const shippingOption = shipping_options?.find((so) => so.id === so_id);
  if (!isPending && !isFetching && !shippingOption) {
    throw new Response(
      JSON.stringify({ message: `Shipping option with ID ${so_id} was not found` }),
      { status: 404, headers: { "Content-Type": "application/json" } }
    );
  }
  if (isError) {
    throw error;
  }
  const isPickup = shippingOption?.service_zone.fulfillment_set.type === "pickup" /* Pickup */;
  return /* @__PURE__ */ jsxs2(RouteDrawer, { "data-testid": "location-shipping-option-edit-drawer", children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { "data-testid": "location-shipping-option-edit-drawer-header", children: /* @__PURE__ */ jsx2(Heading, { "data-testid": "location-shipping-option-edit-drawer-heading", children: t(
      `stockLocations.${isPickup ? "pickupOptions" : "shippingOptions"}.edit.header`
    ) }) }),
    shippingOption && /* @__PURE__ */ jsx2(
      EditShippingOptionForm,
      {
        shippingOption,
        locationId: location_id,
        type: shippingOption.service_zone.fulfillment_set.type
      }
    )
  ] });
};
export {
  LocationServiceZoneShippingOptionEdit as Component
};
