import {
  TargetForm,
  TargetItem,
  TaxRateRuleReferenceSchema,
  createTaxRulePayload
} from "./chunk-YVI3LZ3X.js";
import "./chunk-Q4UVXS46.js";
import {
  PercentageInput
} from "./chunk-MAEP2UCK.js";
import "./chunk-N335VHD3.js";
import "./chunk-EBZ5VZEO.js";
import "./chunk-4F5GP7J7.js";
import "./chunk-7TIZP4YG.js";
import "./chunk-GJM5XI3E.js";
import "./chunk-YNGA3GRX.js";
import "./chunk-BI2AYXZQ.js";
import "./chunk-MG4GKUJW.js";
import "./chunk-AYVH6Q5O.js";
import "./chunk-VOHEQ7B5.js";
import "./chunk-DY3XQPHC.js";
import "./chunk-GRH7C3QN.js";
import "./chunk-VKOE5J66.js";
import "./chunk-42R54Z2X.js";
import "./chunk-Y6S7K3YB.js";
import "./chunk-N3T24SEK.js";
import "./chunk-JHIMVLB2.js";
import "./chunk-HRUO43BZ.js";
import "./chunk-HHD2VUED.js";
import "./chunk-2ZFELO2L.js";
import "./chunk-26OOAKQ6.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-XBKWFLJG.js";
import "./chunk-5ALC4Z2H.js";
import "./chunk-ZC2ME3UB.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-HB3BP55W.js";
import "./chunk-SYNUA6LQ.js";
import "./chunk-UAE6XBYL.js";
import "./chunk-5YZ3G5EZ.js";
import "./chunk-VW56KWO2.js";
import "./chunk-T35QBLG7.js";
import "./chunk-XCHKUSUU.js";
import "./chunk-JRTZWK77.js";
import "./chunk-AAKR2CB4.js";
import "./chunk-G64YUZSL.js";
import "./chunk-BEPAXQMU.js";
import "./chunk-FWPGOIFA.js";
import "./chunk-LFX6R456.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-IQPN4PZJ.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteDrawer,
  StackedDrawer,
  useRouteModal,
  useStackedModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import "./chunk-52KJSIHS.js";
import "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import {
  useProductTags
} from "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import {
  useTaxRate,
  useUpdateTaxRate
} from "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import {
  useProductTypes
} from "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import "./chunk-W34KDYZA.js";
import {
  useCustomerGroups
} from "./chunk-II3CLUXA.js";
import {
  useCollections
} from "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import {
  useProducts
} from "./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/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/index.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/_components/tax-region-tax-override-edit-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { MagnifyingGlass } from "@medusajs/icons";
import {
  Button,
  Divider,
  Heading,
  Hint,
  Input,
  Label,
  Select,
  Text,
  clx,
  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 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()
    // product_collection: z.boolean(),
    // product_tag: z.boolean(),
    // customer_group: z.boolean(),
  }),
  product: z.array(TaxRateRuleReferenceSchema).optional(),
  product_type: 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 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
        // 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
      // 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
      // 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 rules = [
      productRules,
      productTypeRules
      // 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 getControls = (type) => {
    switch (type) {
      case "product" /* PRODUCT */:
        return products;
      case "product_type" /* PRODUCT_TYPE */:
        return productTypes;
      // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
      //   return productCollections
      // case TaxRateRuleReferenceType.PRODUCT_TAG:
      //   return productTags
      // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
      //   return customerGroups
      default:
        return products;
    }
  };
  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: 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"
    ),
    ["product_collection" /* PRODUCT_COLLECTION */]: t(
      "taxRegions.fields.targets.placeholders.product"
    ),
    ["product_tag" /* PRODUCT_TAG */]: t(
      "taxRegions.fields.targets.placeholders.product"
    ),
    ["customer_group" /* CUSTOMER_GROUP */]: t(
      "taxRegions.fields.targets.placeholders.product"
    )
  };
  const getFieldHandler = (type) => {
    const controls = getControls(type);
    const { fields, remove, append } = controls;
    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));
        }
      }
      append(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,
                        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,
                                    {
                                      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.map((field2, index2) => {
                                    return /* @__PURE__ */ jsx(
                                      TargetItem,
                                      {
                                        index: index2,
                                        label: field2.label,
                                        onRemove: remove
                                      },
                                      field2.id
                                    );
                                  }) })
                                ] }) : 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/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/index.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, { 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 */]: [],
    ["product_collection" /* PRODUCT_COLLECTION */]: [],
    ["product_tag" /* PRODUCT_TAG */]: [],
    ["product_type" /* PRODUCT_TYPE */]: [],
    ["customer_group" /* CUSTOMER_GROUP */]: []
  };
  rules.forEach((rule) => {
    const reference = rule.reference;
    idsByReferenceType[reference]?.push(rule.reference_id);
  });
  const queries = [
    {
      ids: idsByReferenceType["product" /* PRODUCT */],
      hook: useProducts,
      key: "product" /* PRODUCT */,
      getResult: (result) => result.products.map((product) => ({
        label: product.title,
        value: product.id
      }))
    },
    {
      ids: idsByReferenceType["product_collection" /* PRODUCT_COLLECTION */],
      hook: useCollections,
      key: "product_collection" /* PRODUCT_COLLECTION */,
      getResult: (result) => result.collections.map((collection) => ({
        label: collection.title,
        value: collection.id
      }))
    },
    {
      ids: idsByReferenceType["product_tag" /* PRODUCT_TAG */],
      hook: useProductTags,
      key: "product_tag" /* PRODUCT_TAG */,
      getResult: (result) => result.tags.map((tag) => ({
        label: tag.value,
        value: tag.id
      }))
    },
    {
      ids: idsByReferenceType["product_type" /* PRODUCT_TYPE */],
      hook: useProductTypes,
      key: "product_type" /* PRODUCT_TYPE */,
      getResult: (result) => result.product_types.map((productType) => ({
        label: productType.value,
        value: productType.id
      }))
    },
    {
      ids: idsByReferenceType["customer_group" /* CUSTOMER_GROUP */],
      hook: useCustomerGroups,
      key: "customer_group" /* CUSTOMER_GROUP */,
      getResult: (result) => result.customer_groups.map((customerGroup) => ({
        label: customerGroup.name,
        value: customerGroup.id
      }))
    }
  ];
  const queryResults = queries.map(({ ids, hook }) => {
    const enabled = ids.length > 0;
    return {
      result: hook({ id: ids, limit: ids.length }, { enabled }),
      enabled
    };
  });
  if (!taxRate) {
    return { isPending: true };
  }
  const isPending = queryResults.some(
    ({ result, enabled }) => enabled && result.isPending
  );
  if (isPending) {
    return { isPending };
  }
  queryResults.forEach(({ result, enabled }) => {
    if (enabled && result.isError) {
      throw result.error;
    }
  });
  const initialRulesValues = queries.reduce(
    (acc, { key, getResult }, index) => ({
      ...acc,
      [key]: queryResults[index].enabled ? getResult(queryResults[index].result) : []
    }),
    {}
  );
  return { initialValues: initialRulesValues, isPending: false };
};
var Component = TaxRegionTaxOverrideEdit;
export {
  Component
};
