import {
  createTaxRulePayload
} from "./chunk-SWL7ZCP3.js";
import {
  TargetForm,
  TargetItem,
  TaxRateRuleReferenceSchema
} from "./chunk-RVAVU222.js";
import "./chunk-5A4JNOK3.js";
import "./chunk-O5VKW5FL.js";
import "./chunk-LTBX54CI.js";
import "./chunk-LQAAVRET.js";
import "./chunk-AFQS6E4N.js";
import "./chunk-QG6PLWNH.js";
import "./chunk-DBYUB2YI.js";
import "./chunk-4F5GP7J7.js";
import "./chunk-54EPH67T.js";
import "./chunk-JQV7CXEC.js";
import {
  PercentageInput
} from "./chunk-MAEP2UCK.js";
import "./chunk-HINXQTCW.js";
import "./chunk-NOWUEJ74.js";
import "./chunk-VW56KWO2.js";
import "./chunk-TZSOL34K.js";
import "./chunk-25LYVP3C.js";
import "./chunk-HC25LNX7.js";
import "./chunk-2Y3WMGN6.js";
import "./chunk-JHIMVLB2.js";
import "./chunk-PXYDR7WQ.js";
import "./chunk-JRTZWK77.js";
import "./chunk-Z5I2Z6L3.js";
import "./chunk-FWPGOIFA.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-WIYFXWRI.js";
import "./chunk-FQERBIVS.js";
import "./chunk-ULJ3OMWU.js";
import "./chunk-YBZWO4ZV.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-3EF54XFY.js";
import "./chunk-IQPN4PZJ.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import "./chunk-BE5QWX5N.js";
import "./chunk-2ZFELO2L.js";
import "./chunk-RT6L7JXU.js";
import "./chunk-26OOAKQ6.js";
import "./chunk-ZQZHFMD7.js";
import "./chunk-6TFS6ET5.js";
import "./chunk-25YTS3TI.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-NNI6QKKZ.js";
import "./chunk-MG4GKUJW.js";
import "./chunk-AYVH6Q5O.js";
import "./chunk-VOHEQ7B5.js";
import "./chunk-C3WE6EFO.js";
import "./chunk-N5IUYCUZ.js";
import "./chunk-7SVLKK6Q.js";
import "./chunk-GR6JUIRU.js";
import "./chunk-PVZBDWLK.js";
import "./chunk-3B6MTW5G.js";
import "./chunk-VKOE5J66.js";
import "./chunk-DY3XQPHC.js";
import "./chunk-WSR2ZXAJ.js";
import "./chunk-VVWB3GIK.js";
import "./chunk-KBYZLKI4.js";
import "./chunk-YWWUOGJA.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteDrawer,
  StackedDrawer,
  useRouteModal,
  useStackedModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import {
  useTaxRate,
  useUpdateTaxRate
} from "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import {
  useProductTypes
} from "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import {
  useShippingOptions
} from "./chunk-O4STPJR2.js";
import "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import {
  useProducts
} from "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/tax-regions/tax-region-tax-override-edit/tax-region-tax-override-edit.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/tax-regions/tax-region-tax-override-edit/components/tax-region-tax-override-edit-form/tax-region-tax-override-edit-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { MagnifyingGlass } from "@medusajs/icons";
import {
  Button,
  clx,
  Divider,
  Heading,
  Hint,
  Input,
  Label,
  Select,
  Text,
  toast
} from "@medusajs/ui";
import { useFieldArray, useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var DISPLAY_OVERRIDE_ITEMS_LIMIT = 10;
var STACKED_MODAL_ID = "tr";
var getStackedModalId = (type) => `${STACKED_MODAL_ID}-${type}`;
var TaxRegionTaxRateEditSchema = z.object({
  name: z.string().min(1),
  code: z.string().min(1),
  rate: z.object({
    float: z.number().optional(),
    value: z.string().optional()
  }),
  is_combinable: z.boolean().optional(),
  enabled_rules: z.object({
    product: z.boolean(),
    product_type: z.boolean(),
    shipping_option: z.boolean()
    // product_collection: z.boolean(),
    // product_tag: z.boolean(),
    // customer_group: z.boolean(),
  }),
  product: z.array(TaxRateRuleReferenceSchema).optional(),
  product_type: z.array(TaxRateRuleReferenceSchema).optional(),
  shipping_option: z.array(TaxRateRuleReferenceSchema).optional()
  // product_collection: z.array(TaxRateRuleReferenceSchema).optional(),
  // product_tag: z.array(TaxRateRuleReferenceSchema).optional(),
  // customer_group: z.array(TaxRateRuleReferenceSchema).optional(),
});
var TaxRegionTaxOverrideEditForm = ({
  taxRate,
  isCombinable = false,
  initialValues
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { setIsOpen } = useStackedModal();
  const direction = useDocumentDirection();
  const form = useForm({
    defaultValues: {
      name: taxRate.name,
      code: taxRate.code,
      rate: {
        value: taxRate.rate?.toString() || ""
      },
      is_combinable: taxRate.is_combinable,
      enabled_rules: {
        product: initialValues.product.length > 0,
        product_type: initialValues.product_type.length > 0,
        shipping_option: initialValues.shipping_option.length > 0
        // customer_groups: initialValues.customer_group.length > 0,
        // product_collections:
        //   initialValues.product_collections.length > 0,
        // product_tags: initialValues.product_tag.length > 0,
      },
      product: initialValues.product,
      product_type: initialValues.product_type,
      shipping_option: initialValues.shipping_option
      // product_collections: initialValues.product_collection,
      // product_tags: initialValues.product_tag,
      // customer_groups: initialValues.customer_group,
    },
    resolver: zodResolver(TaxRegionTaxRateEditSchema)
  });
  const { mutateAsync, isPending } = useUpdateTaxRate(taxRate.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const {
      product,
      product_type,
      shipping_option
      // customer_groups,
      // product_collections,
      // product_tags,
    } = values;
    const productRules = createTaxRulePayload({
      reference_type: "product" /* PRODUCT */,
      references: product || []
    });
    const productTypeRules = createTaxRulePayload({
      reference_type: "product_type" /* PRODUCT_TYPE */,
      references: product_type || []
    });
    const shippingOptionRules = createTaxRulePayload({
      reference_type: "shipping_option" /* SHIPPING_OPTION */,
      references: shipping_option || []
    });
    const rules = [
      productRules,
      productTypeRules,
      shippingOptionRules
      // customerGroupRules,
      // productCollectionRules,
      // productTagRules,
    ].filter((rule) => Boolean(rule)).flatMap((r) => r);
    await mutateAsync(
      {
        name: values.name,
        code: values.code || "",
        rate: values.rate?.float,
        is_combinable: values.is_combinable,
        rules
      },
      {
        onSuccess: () => {
          toast.success(t("taxRegions.taxRates.edit.successToast"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const products = useFieldArray({
    control: form.control,
    name: "product"
  });
  const productTypes = useFieldArray({
    control: form.control,
    name: "product_type"
  });
  const shippingOptions = useFieldArray({
    control: form.control,
    name: "shipping_option"
  });
  const getControls = (type) => {
    switch (type) {
      case "product" /* PRODUCT */:
        return products;
      case "product_type" /* PRODUCT_TYPE */:
        return productTypes;
      case "shipping_option" /* SHIPPING_OPTION */:
        return shippingOptions;
    }
  };
  const referenceTypeOptions = [
    {
      value: "product" /* PRODUCT */,
      label: t("taxRegions.fields.targets.options.product")
    },
    {
      value: "product_type" /* PRODUCT_TYPE */,
      label: t("taxRegions.fields.targets.options.productType")
    },
    {
      value: "shipping_option" /* SHIPPING_OPTION */,
      label: t("taxRegions.fields.targets.options.shippingOption")
    }
    // {
    //   value: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
    //   label: t("taxRegions.fields.targets.options.productCollection"),
    // },
    // {
    //   value: TaxRateRuleReferenceType.PRODUCT_TAG,
    //   label: t("taxRegions.fields.targets.options.productTag"),
    // },
    // {
    //   value: TaxRateRuleReferenceType.CUSTOMER_GROUP,
    //   label: t("taxRegions.fields.targets.options.customerGroup"),
    // },
  ];
  const searchPlaceholders = {
    ["product" /* PRODUCT */]: t(
      "taxRegions.fields.targets.placeholders.product"
    ),
    ["product_type" /* PRODUCT_TYPE */]: t(
      "taxRegions.fields.targets.placeholders.productType"
    ),
    ["shipping_option" /* SHIPPING_OPTION */]: t(
      "taxRegions.fields.targets.placeholders.shippingOption"
    )
    // [TaxRateRuleReferenceType.PRODUCT_COLLECTION]: t(
    //   "taxRegions.fields.targets.placeholders.productCollection"
    // ),
    // [TaxRateRuleReferenceType.PRODUCT_TAG]: t(
    //   "taxRegions.fields.targets.placeholders.productTag"
    // ),
    // [TaxRateRuleReferenceType.CUSTOMER_GROUP]: t(
    //   "taxRegions.fields.targets.placeholders.customerGroup"
    // ),
  };
  const getFieldHandler = (type) => {
    const { fields, remove, prepend } = getControls(type);
    const modalId = getStackedModalId(type);
    return (references) => {
      if (!references.length) {
        form.setValue(type, [], {
          shouldDirty: true
        });
        setIsOpen(modalId, false);
        return;
      }
      const newIds = references.map((reference) => reference.value);
      const fieldsToAdd = references.filter(
        (reference) => !fields.some((field) => field.value === reference.value)
      );
      for (const field of fields) {
        if (!newIds.includes(field.value)) {
          remove(fields.indexOf(field));
        }
      }
      prepend(fieldsToAdd);
      setIsOpen(modalId, false);
    };
  };
  const displayOrder = /* @__PURE__ */ new Set([
    "product" /* PRODUCT */
  ]);
  const disableRule = (type) => {
    form.setValue(type, [], {
      shouldDirty: true
    });
    form.setValue(`enabled_rules.${type}`, false, {
      shouldDirty: true
    });
    displayOrder.delete(type);
  };
  const enableRule = (type) => {
    form.setValue(`enabled_rules.${type}`, true, {
      shouldDirty: true
    });
    form.setValue(type, [], {
      shouldDirty: true
    });
    displayOrder.add(type);
  };
  const watchedEnabledRules = useWatch({
    control: form.control,
    name: "enabled_rules"
  });
  const addRule = () => {
    const firstDisabledRule = Object.keys(watchedEnabledRules).find(
      (key) => !watchedEnabledRules[key]
    );
    if (firstDisabledRule) {
      enableRule(firstDisabledRule);
    }
  };
  const visibleRuleTypes = referenceTypeOptions.filter((option) => watchedEnabledRules[option.value]).sort((a, b) => {
    const orderArray = Array.from(displayOrder);
    return orderArray.indexOf(a.value) - orderArray.indexOf(b.value);
  });
  const getAvailableRuleTypes = (type) => {
    return referenceTypeOptions.filter((option) => {
      return !visibleRuleTypes.some(
        (visibleOption) => visibleOption.value === option.value
      ) || option.value === type;
    });
  };
  const showAddButton = Object.values(watchedEnabledRules).some(
    (value) => !value
  );
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex flex-1 flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-6 overflow-auto", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", 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: "code",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("taxRegions.fields.taxCode") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "rate",
                render: ({ field: { value, onChange, ...field } }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("taxRegions.fields.taxRate") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      PercentageInput,
                      {
                        ...field,
                        value: value?.value,
                        decimalsLimit: 4,
                        onValueChange: (value2, _name, values) => onChange({
                          value: value2,
                          float: values?.float
                        })
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            )
          ] }),
          isCombinable && /* @__PURE__ */ jsx(
            SwitchBox,
            {
              control: form.control,
              name: "is_combinable",
              label: t("taxRegions.fields.isCombinable.label"),
              description: t("taxRegions.fields.isCombinable.hint")
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-x-4", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
                  /* @__PURE__ */ jsx(Label, { id: "tax_region_rules_label", htmlFor: "tax_region_rules", children: t("taxRegions.fields.targets.label") }),
                  /* @__PURE__ */ jsxs(
                    Text,
                    {
                      size: "small",
                      leading: "compact",
                      className: "text-ui-fg-muted",
                      children: [
                        "(",
                        t("fields.optional"),
                        ")"
                      ]
                    }
                  )
                ] }),
                /* @__PURE__ */ jsx(Hint, { id: "tax_region_rules_description", className: "text-pretty", children: t("taxRegions.fields.targets.hint") })
              ] }),
              showAddButton && /* @__PURE__ */ jsx(
                Button,
                {
                  onClick: addRule,
                  type: "button",
                  size: "small",
                  variant: "transparent",
                  className: "text-ui-fg-interactive hover:text-ui-fg-interactive-hover flex-shrink-0",
                  children: t("taxRegions.fields.targets.action")
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              "div",
              {
                id: "tax_region_rules",
                "aria-labelledby": "tax_region_rules_label",
                "aria-describedby": "tax_region_rules_description",
                role: "application",
                className: "flex flex-col gap-y-3",
                children: visibleRuleTypes.map((ruleType, index) => {
                  const type = ruleType.value;
                  const label = ruleType.label;
                  const isLast = index === visibleRuleTypes.length - 1;
                  const searchPlaceholder = searchPlaceholders[type];
                  const options = getAvailableRuleTypes(type);
                  const modalId = getStackedModalId(type);
                  const { fields, remove } = getControls(type);
                  const handler = getFieldHandler(type);
                  const handleChangeType = (value) => {
                    disableRule(type);
                    enableRule(value);
                  };
                  return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: ruleType.value,
                      render: ({
                        field: { value: _value, onChange: _onChange, ...field }
                      }) => {
                        return /* @__PURE__ */ jsxs(Form.Item, { className: "space-y-0", children: [
                          /* @__PURE__ */ jsx(Form.Label, { className: "sr-only", children: label }),
                          /* @__PURE__ */ jsxs(
                            "div",
                            {
                              className: clx(
                                "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
                                "aria-[invalid='true']:shadow-borders-error"
                              ),
                              role: "application",
                              ...field,
                              children: [
                                /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2", children: [
                                  isLast ? /* @__PURE__ */ jsxs(
                                    Select,
                                    {
                                      dir: direction,
                                      value: type,
                                      onValueChange: handleChangeType,
                                      children: [
                                        /* @__PURE__ */ jsx(Select.Trigger, { className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover", children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                                        /* @__PURE__ */ jsx(Select.Content, { children: options.map((option) => {
                                          return /* @__PURE__ */ jsx(
                                            Select.Item,
                                            {
                                              value: option.value,
                                              children: option.label
                                            },
                                            option.value
                                          );
                                        }) })
                                      ]
                                    }
                                  ) : /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5", children: label }),
                                  /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5", children: t("taxRegions.fields.targets.operators.in") })
                                ] }),
                                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 px-1.5", children: [
                                  /* @__PURE__ */ jsxs(StackedDrawer, { id: modalId, children: [
                                    /* @__PURE__ */ jsx(StackedDrawer.Trigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                                      "button",
                                      {
                                        type: "button",
                                        className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none",
                                        children: [
                                          /* @__PURE__ */ jsx(MagnifyingGlass, {}),
                                          searchPlaceholder
                                        ]
                                      }
                                    ) }),
                                    /* @__PURE__ */ jsx(StackedDrawer.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", children: t("actions.browse") }) }),
                                    /* @__PURE__ */ jsxs(StackedDrawer.Content, { children: [
                                      /* @__PURE__ */ jsxs(StackedDrawer.Header, { children: [
                                        /* @__PURE__ */ jsx(StackedDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: t(
                                          "taxRegions.fields.targets.modal.header"
                                        ) }) }),
                                        /* @__PURE__ */ jsx(StackedDrawer.Description, { className: "sr-only", children: t("taxRegions.fields.targets.hint") })
                                      ] }),
                                      /* @__PURE__ */ jsx(
                                        TargetForm,
                                        {
                                          type: "drawer",
                                          referenceType: type,
                                          state: fields,
                                          setState: handler
                                        }
                                      )
                                    ] })
                                  ] }),
                                  /* @__PURE__ */ jsx(
                                    Button,
                                    {
                                      variant: "secondary",
                                      onClick: () => disableRule(type),
                                      type: "button",
                                      children: t("actions.delete")
                                    }
                                  )
                                ] }),
                                fields.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1.5", children: [
                                  /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
                                  /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-1.5 px-1.5", children: fields.slice(0, DISPLAY_OVERRIDE_ITEMS_LIMIT).map((field2, index2) => {
                                    return /* @__PURE__ */ jsx(
                                      TargetItem,
                                      {
                                        index: index2,
                                        label: field2.label,
                                        value: field2.value,
                                        onRemove: remove
                                      },
                                      field2.id
                                    );
                                  }) }),
                                  fields.length > DISPLAY_OVERRIDE_ITEMS_LIMIT && /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-1.5 px-1.5", children: /* @__PURE__ */ jsx("div", { className: "text-ui-fg-muted txt-small flex flex-col gap-y-1.5 px-1.5", children: t("general.plusCountMore", {
                                    count: fields.length - DISPLAY_OVERRIDE_ITEMS_LIMIT
                                  }) }) })
                                ] }) : null
                              ]
                            }
                          ),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, { className: "mt-2" })
                        ] });
                      }
                    }
                  ) }, type);
                })
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { className: "shrink-0", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/tax-regions/tax-region-tax-override-edit/tax-region-tax-override-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var TaxRegionTaxOverrideEdit = () => {
  const { t } = useTranslation2();
  const { tax_rate_id } = useParams();
  const { tax_rate, isPending, isError, error } = useTaxRate(tax_rate_id);
  const { initialValues, isPending: isInitializing } = useDefaultRulesValues(tax_rate);
  const ready = !isPending && !!tax_rate && !isInitializing && !!initialValues;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { prev: "../..", children: [
    /* @__PURE__ */ jsxs2(RouteDrawer.Header, { children: [
      /* @__PURE__ */ jsx2(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx2(Heading2, { children: t("taxRegions.taxOverrides.edit.header") }) }),
      /* @__PURE__ */ jsx2(RouteDrawer.Description, { className: "sr-only", children: t("taxRegions.taxOverrides.edit.hint") })
    ] }),
    ready && /* @__PURE__ */ jsx2(
      TaxRegionTaxOverrideEditForm,
      {
        taxRate: tax_rate,
        isCombinable: true,
        initialValues
      }
    )
  ] });
};
var useDefaultRulesValues = (taxRate) => {
  const rules = taxRate?.rules || [];
  const idsByReferenceType = {
    ["product" /* PRODUCT */]: [],
    // [TaxRateRuleReferenceType.PRODUCT_COLLECTION]: [],
    // [TaxRateRuleReferenceType.PRODUCT_TAG]: [],
    ["product_type" /* PRODUCT_TYPE */]: [],
    ["shipping_option" /* SHIPPING_OPTION */]: []
    // [TaxRateRuleReferenceType.CUSTOMER_GROUP]: [],
  };
  rules.sort((a, b) => a.created_at && b.created_at ? a.created_at.localeCompare(b.created_at) : 0).forEach((rule) => {
    const reference = rule.reference;
    if (reference in idsByReferenceType) {
      idsByReferenceType[reference]?.push(rule.reference_id);
    }
  });
  const productIds = idsByReferenceType["product" /* PRODUCT */];
  const productTypeIds = idsByReferenceType["product_type" /* PRODUCT_TYPE */];
  const shippingOptionIds = idsByReferenceType["shipping_option" /* SHIPPING_OPTION */];
  const queryResults = [
    {
      result: useProducts(
        {
          id: productIds.length > DISPLAY_OVERRIDE_ITEMS_LIMIT ? productIds.slice(0, DISPLAY_OVERRIDE_ITEMS_LIMIT) : productIds,
          limit: DISPLAY_OVERRIDE_ITEMS_LIMIT
        },
        { enabled: productIds.length > 0 }
      ),
      enabled: productIds.length > 0
    },
    {
      result: useProductTypes(
        {
          id: productTypeIds.length > DISPLAY_OVERRIDE_ITEMS_LIMIT ? productTypeIds.slice(0, DISPLAY_OVERRIDE_ITEMS_LIMIT) : productTypeIds,
          limit: DISPLAY_OVERRIDE_ITEMS_LIMIT
        },
        { enabled: productTypeIds.length > 0 }
      ),
      enabled: productTypeIds.length > 0
    },
    {
      result: useShippingOptions(
        {
          id: shippingOptionIds.length > DISPLAY_OVERRIDE_ITEMS_LIMIT ? shippingOptionIds.slice(0, DISPLAY_OVERRIDE_ITEMS_LIMIT) : shippingOptionIds,
          limit: DISPLAY_OVERRIDE_ITEMS_LIMIT
        },
        { enabled: shippingOptionIds.length > 0 }
      ),
      enabled: shippingOptionIds.length > 0
    }
  ];
  if (!taxRate) {
    return { isPending: true, initialValues: { product: [], product_type: [], shipping_option: [] } };
  }
  const isPending = queryResults.some(
    ({ result, enabled }) => enabled && result.isPending
  );
  if (isPending) {
    return { isPending: true, initialValues: { product: [], product_type: [], shipping_option: [] } };
  }
  queryResults.forEach(({ result, enabled }) => {
    if (enabled && result.isError) {
      throw result.error;
    }
  });
  const initialRulesValues = {
    ["product" /* PRODUCT */]: [],
    ["product_type" /* PRODUCT_TYPE */]: [],
    ["shipping_option" /* SHIPPING_OPTION */]: []
  };
  const productsResult = queryResults[0];
  if (productsResult.enabled) {
    const result = productsResult.result;
    if (result.products) {
      const productMap = new Map(
        result.products.map((product) => [product.id, product.title])
      );
      initialRulesValues.product = idsByReferenceType["product" /* PRODUCT */].map((id) => ({
        value: id,
        label: productMap.get(id) || ""
      }));
    }
  }
  const productTypesResult = queryResults[1];
  if (productTypesResult.enabled) {
    const result = productTypesResult.result;
    if (result.product_types) {
      const productTypeMap = new Map(
        result.product_types.map((type) => [type.id, type.value])
      );
      initialRulesValues.product_type = idsByReferenceType["product_type" /* PRODUCT_TYPE */].map((id) => ({
        value: id,
        label: productTypeMap.get(id) || ""
      }));
    }
  }
  const shippingOptionsResult = queryResults[2];
  if (shippingOptionsResult.enabled) {
    const result = shippingOptionsResult.result;
    if (result.shipping_options) {
      const shippingOptionMap = new Map(
        result.shipping_options.map((option) => [option.id, option.name])
      );
      initialRulesValues.shipping_option = idsByReferenceType["shipping_option" /* SHIPPING_OPTION */].map((id) => ({
        value: id,
        label: shippingOptionMap.get(id) || ""
      }));
    }
  }
  return { initialValues: initialRulesValues, isPending: false };
};
export {
  TaxRegionTaxOverrideEdit as Component
};
