import {
  TargetForm,
  TargetItem,
  TaxRateRuleReferenceSchema
} from "./chunk-NHAOR25V.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-KYPPQGGE.js";
import "./chunk-ZMC7BKLT.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-634XVU3D.js";
import {
  currencies,
  getCurrencySymbol
} from "./chunk-IQPN4PZJ.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-KOURHC2N.js";
import "./chunk-2ZFELO2L.js";
import "./chunk-RT6L7JXU.js";
import "./chunk-26OOAKQ6.js";
import "./chunk-ZQZHFMD7.js";
import "./chunk-I5THQVYP.js";
import "./chunk-VIGX66F7.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-HO7Z6MC3.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-ZZO3INVE.js";
import "./chunk-PVZBDWLK.js";
import "./chunk-3B6MTW5G.js";
import "./chunk-VKOE5J66.js";
import "./chunk-DY3XQPHC.js";
import "./chunk-LNAXUDW2.js";
import "./chunk-VVWB3GIK.js";
import "./chunk-HKDFWQ6Q.js";
import "./chunk-SESTTUVM.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteDrawer,
  StackedDrawer,
  useRouteModal,
  useStackedModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-PBQ5M44A.js";
import "./chunk-OH4AABUT.js";
import "./chunk-YKDEE7ZL.js";
import "./chunk-AEMDNTW5.js";
import "./chunk-LYD3C73Z.js";
import "./chunk-7O5NDICV.js";
import "./chunk-46M463BR.js";
import "./chunk-YFRC6GEN.js";
import "./chunk-N6SI4IIT.js";
import "./chunk-JPNPTILP.js";
import "./chunk-DAXXLQKB.js";
import {
  useBatchCommissionRules,
  useCommissionRate,
  useUpdateCommissionRate
} from "./chunk-OHOWEMHO.js";
import "./chunk-GKGLVDDV.js";
import "./chunk-WJJXUXSO.js";
import "./chunk-LAPEZATU.js";
import "./chunk-DBNPVU3L.js";
import "./chunk-U7WZYWGA.js";
import "./chunk-ZN7LWXVC.js";
import "./chunk-VYMODH6P.js";
import "./chunk-LEG67A2R.js";
import "./chunk-PRBE5CM3.js";
import "./chunk-5TRY5IMZ.js";
import "./chunk-TAKEQAZZ.js";
import "./chunk-B6FG7A6W.js";
import "./chunk-EPHVGD5Z.js";
import "./chunk-ESPLVOFC.js";
import {
  useStore
} from "./chunk-FXWKGNRV.js";
import "./chunk-VDKOJ5WD.js";
import "./chunk-DL2ZIXBO.js";
import "./chunk-Z2QQZOG3.js";
import "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/commission-rates/commission-rate-edit/commission-rate-edit.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/commission-rates/commission-rate-edit/components/edit-commission-rate-form/edit-commission-rate-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { MagnifyingGlass } from "@medusajs/icons";
import {
  Button,
  clx,
  CurrencyInput,
  Divider,
  Heading,
  Hint,
  Input,
  Label,
  Select,
  Switch,
  Text,
  toast
} from "@medusajs/ui";
import { useFieldArray, useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var STACKED_MODAL_ID = "cr";
var getStackedModalId = (type) => `${STACKED_MODAL_ID}-${type}`;
var EditCommissionRateSchema = zod.object({
  name: zod.string().min(1),
  code: zod.string().min(1),
  type: zod.enum(["fixed", "percentage"]),
  target: zod.enum(["item", "shipping"]),
  value: zod.coerce.number().min(0),
  currency_code: zod.string().optional(),
  min_amount: zod.coerce.number().optional(),
  include_tax: zod.boolean(),
  priority: zod.coerce.number().int().min(0),
  enabled_rules: zod.object({
    product: zod.boolean(),
    product_type: zod.boolean(),
    shipping_option: zod.boolean()
  }),
  product: zod.array(TaxRateRuleReferenceSchema).optional(),
  product_type: zod.array(TaxRateRuleReferenceSchema).optional(),
  shipping_option: zod.array(TaxRateRuleReferenceSchema).optional()
});
var getRulesByType = (rules, type) => {
  return (rules || []).filter((r) => r.reference === type).map((r) => ({ value: r.reference_id, label: "" }));
};
var EditCommissionRateForm = ({
  commissionRate
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { setIsOpen } = useStackedModal();
  const direction = useDocumentDirection();
  const initialProducts = getRulesByType(
    commissionRate.rules,
    "product" /* PRODUCT */
  );
  const initialProductTypes = getRulesByType(
    commissionRate.rules,
    "product_type" /* PRODUCT_TYPE */
  );
  const initialShippingOptions = getRulesByType(
    commissionRate.rules,
    "shipping_option" /* SHIPPING_OPTION */
  );
  const form = useForm({
    defaultValues: {
      name: commissionRate.name,
      code: commissionRate.code,
      type: commissionRate.type,
      target: commissionRate.target,
      value: commissionRate.value,
      currency_code: commissionRate.currency_code ?? "",
      min_amount: commissionRate.min_amount ?? void 0,
      include_tax: commissionRate.include_tax,
      priority: commissionRate.priority,
      enabled_rules: {
        product: initialProducts.length > 0,
        product_type: initialProductTypes.length > 0,
        shipping_option: initialShippingOptions.length > 0
      },
      product: initialProducts,
      product_type: initialProductTypes,
      shipping_option: initialShippingOptions
    },
    resolver: zodResolver(EditCommissionRateSchema)
  });
  const { store } = useStore();
  const storeCurrencies = (store?.supported_currencies ?? []).map(
    (c) => currencies[c.currency_code.toUpperCase()]
  );
  const { mutateAsync: updateCommissionRate, isPending: isUpdating } = useUpdateCommissionRate(commissionRate.id);
  const { mutateAsync: batchRules, isPending: isBatching } = useBatchCommissionRules(commissionRate.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const newRules = [
      ...(values.product || []).map((ref) => ({
        reference: "product" /* PRODUCT */,
        reference_id: ref.value
      })),
      ...(values.product_type || []).map((ref) => ({
        reference: "product_type" /* PRODUCT_TYPE */,
        reference_id: ref.value
      })),
      ...(values.shipping_option || []).map((ref) => ({
        reference: "shipping_option" /* SHIPPING_OPTION */,
        reference_id: ref.value
      }))
    ];
    const existingRules = commissionRate.rules || [];
    const toCreate = newRules.filter(
      (nr) => !existingRules.some(
        (er) => er.reference === nr.reference && er.reference_id === nr.reference_id
      )
    );
    const toDelete = existingRules.filter(
      (er) => !newRules.some(
        (nr) => nr.reference === er.reference && nr.reference_id === er.reference_id
      )
    ).map((er) => er.id);
    try {
      await updateCommissionRate({
        name: values.name,
        code: values.code,
        type: values.type,
        target: values.target,
        value: values.value,
        currency_code: values.currency_code || null,
        min_amount: values.min_amount ?? null,
        include_tax: values.include_tax,
        priority: values.priority
      });
      if (toCreate.length > 0 || toDelete.length > 0) {
        await batchRules({
          ...toCreate.length > 0 ? { create: toCreate } : {},
          ...toDelete.length > 0 ? { delete: toDelete } : {}
        });
      }
      toast.success(t("commissionRates.edit.successToast"));
      handleSuccess();
    } catch (e) {
      toast.error(e.message);
    }
  });
  const watchType = form.watch("type");
  const watchCurrency = form.watch("currency_code");
  const products = useFieldArray({
    control: form.control,
    name: "product" /* PRODUCT */
  });
  const productTypes = useFieldArray({
    control: form.control,
    name: "product_type" /* PRODUCT_TYPE */
  });
  const shippingOptions = useFieldArray({
    control: form.control,
    name: "shipping_option" /* 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")
    }
  ];
  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"
    )
  };
  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 = new Set(
    [
      initialProducts.length > 0 ? "product" /* PRODUCT */ : null,
      initialProductTypes.length > 0 ? "product_type" /* PRODUCT_TYPE */ : null,
      initialShippingOptions.length > 0 ? "shipping_option" /* SHIPPING_OPTION */ : null
    ].filter(Boolean)
  );
  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
  );
  const isPending = isUpdating || isBatching;
  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: "grid grid-cols-1 gap-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "name",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.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 }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.code") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "type",
                render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.type.label") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { ...field, onValueChange: onChange, children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                    /* @__PURE__ */ jsxs(Select.Content, { children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: "percentage", children: t("commissionRates.fields.type.percentage") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: "fixed", children: t("commissionRates.fields.type.fixed") })
                    ] })
                  ] }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "target",
                render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.target.label") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { ...field, onValueChange: onChange, children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                    /* @__PURE__ */ jsxs(Select.Content, { children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: "item", children: t("commissionRates.fields.target.item") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: "shipping", children: t("commissionRates.fields.target.shipping") })
                    ] })
                  ] }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "currency_code",
                render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.currencyCode") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { ...field, onValueChange: onChange, children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, children: /* @__PURE__ */ jsx(Select.Value, { placeholder: t("commissionRates.fields.currencyPlaceholder") }) }),
                    /* @__PURE__ */ jsx(Select.Content, { children: storeCurrencies.map((currency) => /* @__PURE__ */ jsx(
                      Select.Item,
                      {
                        value: currency.code.toLowerCase(),
                        children: currency.name
                      },
                      currency.code
                    )) })
                  ] }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "value",
                render: ({ field: { value, onChange, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.rate") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: watchType === "percentage" ? /* @__PURE__ */ jsx(
                    PercentageInput,
                    {
                      ...field,
                      value,
                      decimalsLimit: 4,
                      onValueChange: (_value, _name, values) => onChange(values?.float ?? 0)
                    }
                  ) : /* @__PURE__ */ jsx(
                    CurrencyInput,
                    {
                      min: 0,
                      onValueChange: (value2) => onChange(value2 ? parseInt(value2) : ""),
                      code: watchCurrency ?? "",
                      symbol: watchCurrency ? getCurrencySymbol(watchCurrency) : "",
                      ...field,
                      value
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "min_amount",
                render: ({ field: { value, onChange, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.minAmount") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                    CurrencyInput,
                    {
                      min: 0,
                      onValueChange: (value2) => onChange(value2 ? parseInt(value2) : ""),
                      code: watchCurrency ?? "",
                      symbol: watchCurrency ? getCurrencySymbol(watchCurrency) : "",
                      ...field,
                      value
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "priority",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.priority") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "number", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "include_tax",
                render: ({ field: { value, onChange, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("commissionRates.fields.includeTax") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      Switch,
                      {
                        ...field,
                        checked: value,
                        onCheckedChange: onChange
                      }
                    ) })
                  ] }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            )
          ] }),
          /* @__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: "commission_rules_label", htmlFor: "commission_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: "commission_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: "commission_rules",
                "aria-labelledby": "commission_rules_label",
                "aria-describedby": "commission_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.map((field2, index2) => {
                                    return /* @__PURE__ */ jsx(
                                      TargetItem,
                                      {
                                        index: index2,
                                        label: field2.label,
                                        value: field2.value,
                                        onRemove: remove
                                      },
                                      field2.id
                                    );
                                  }) })
                                ] }) : null
                              ]
                            }
                          ),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, { className: "mt-2" })
                        ] });
                      }
                    }
                  ) }, type);
                })
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxs(RouteDrawer.Footer, { 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/commission-rates/commission-rate-edit/commission-rate-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CommissionRateEdit = () => {
  const { t } = useTranslation2();
  const { id } = useParams();
  const {
    commission_rate,
    isPending: isLoading,
    isError,
    error
  } = useCommissionRate(id, { fields: "*rules" });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(Heading2, { children: t("commissionRates.edit.header") }) }),
    !isLoading && commission_rate && /* @__PURE__ */ jsx2(EditCommissionRateForm, { commissionRate: commission_rate })
  ] });
};
export {
  CommissionRateEdit as Component
};
