import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  usePromotionRuleAttributes,
  usePromotionRules
} from "./chunk-HAFZQK53.js";
import {
  useStore
} from "./chunk-LC6TM5OT.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";

// src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
import { forwardRef, Fragment, useEffect as useEffect2, useRef } from "react";
import { XMarkMini } from "@medusajs/icons";
import { Badge, Button, Heading, IconButton, Select, Text } from "@medusajs/ui";
import { useFieldArray, useWatch as useWatch2 } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/promotions/common/edit-rules/components/edit-rules-form/utils.ts
var generateRuleAttributes = (rules) => (rules || []).map((rule) => ({
  id: rule.id,
  required: rule.required,
  field_type: rule.field_type,
  disguised: rule.disguised,
  attribute: rule.attribute,
  operator: rule.operator,
  values: rule.field_type === "number" || rule.operator === "eq" ? typeof rule.values === "object" ? rule.values[0]?.value : rule.values : rule?.values?.map((v) => v.value)
}));

// src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
import { useEffect } from "react";
import { Input } from "@medusajs/ui";
import { useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var buildFilters = (attribute, store) => {
  if (!attribute || !store) {
    return {};
  }
  if (attribute === "currency_code") {
    return {
      value: store.supported_currencies?.map((c) => c.currency_code)
    };
  }
  return {};
};
var RuleValueFormField = ({
  form,
  identifier,
  scope,
  name,
  operator,
  fieldRule,
  attributes,
  ruleType,
  applicationMethodTargetType
}) => {
  const { t } = useTranslation();
  const attribute = attributes?.find(
    (attr) => attr.value === fieldRule.attribute
  );
  const { store, isLoading: isStoreLoading } = useStore();
  const watchValue = useWatch({
    control: form.control,
    name
  });
  const comboboxData = useComboboxData({
    queryFn: async (params) => {
      return await sdk.admin.promotions.ruleValueOptions.$ruleType.$ruleAttributeId.query({
        $ruleType: ruleType,
        $ruleAttributeId: attribute?.id,
        ...params,
        ...buildFilters(attribute?.id, store),
        application_method_target_type: applicationMethodTargetType
      });
    },
    enabled: !!attribute?.id && ["select", "multiselect"].includes(attribute.field_type) && !isStoreLoading,
    getOptions: (data) => data.values,
    queryKey: ["rule-value-options", ruleType, attribute?.id],
    defaultValue: watchValue,
    defaultValueKey: "value"
  });
  const watchOperator = useWatch({
    control: form.control,
    name: operator
  });
  useEffect(() => {
    const hasDirtyRules = Object.keys(form.formState.dirtyFields).length > 0;
    if (!hasDirtyRules) {
      return;
    }
    if (watchOperator === "eq") {
      form.setValue(name, "");
    } else {
      form.setValue(name, []);
    }
  }, [watchOperator]);
  const fieldIndex = name.split(".").slice(-2, -1)[0];
  const testIdBase = `rule-value-form-field-${ruleType}-${fieldIndex}`;
  return /* @__PURE__ */ jsx(
    Form.Field,
    {
      name,
      render: ({ field: { onChange, ref, ...field } }) => {
        if (attribute?.field_type === "number") {
          return /* @__PURE__ */ jsxs(
            Form.Item,
            {
              className: "basis-1/2",
              "data-testid": `${testIdBase}-number-item`,
              children: [
                /* @__PURE__ */ jsx(Form.Control, { "data-testid": `${testIdBase}-number-control`, children: /* @__PURE__ */ jsx(
                  Input,
                  {
                    ...field,
                    type: "number",
                    onChange,
                    className: "bg-ui-bg-base",
                    ref,
                    min: 1,
                    disabled: !fieldRule.attribute,
                    "data-testid": `${testIdBase}-number-input`
                  }
                ) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": `${testIdBase}-number-error` })
              ]
            }
          );
        } else if (attribute?.field_type === "text") {
          return /* @__PURE__ */ jsxs(
            Form.Item,
            {
              className: "basis-1/2",
              "data-testid": `${testIdBase}-text-item`,
              children: [
                /* @__PURE__ */ jsx(Form.Control, { "data-testid": `${testIdBase}-text-control`, children: /* @__PURE__ */ jsx(
                  Input,
                  {
                    ...field,
                    ref,
                    onChange,
                    className: "bg-ui-bg-base",
                    disabled: !fieldRule.attribute,
                    "data-testid": `${testIdBase}-text-input`
                  }
                ) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": `${testIdBase}-text-error` })
              ]
            }
          );
        } else {
          return /* @__PURE__ */ jsxs(
            Form.Item,
            {
              className: "basis-1/2",
              "data-testid": `${testIdBase}-combobox-item`,
              children: [
                /* @__PURE__ */ jsx(Form.Control, { "data-testid": `${testIdBase}-combobox-control`, children: /* @__PURE__ */ jsx(
                  Combobox,
                  {
                    ...field,
                    ...comboboxData,
                    ref,
                    placeholder: watchOperator === "eq" ? t("labels.selectValue") : t("labels.selectValues"),
                    disabled: !watchOperator,
                    onChange,
                    "data-testid": `${testIdBase}-combobox`
                  }
                ) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": `${testIdBase}-combobox-error` })
              ]
            }
          );
        }
      }
    },
    `${identifier}.${scope}.${name}-${fieldRule.attribute}`
  );
};

// src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
var requiredProductRule = {
  id: "product",
  attribute: "items.product.id",
  attribute_label: "Product",
  operator: "eq",
  operator_label: "Equal",
  values: [],
  required: true,
  field_type: "select",
  disguised: false
};

// src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var RulesFormField = ({
  form,
  ruleType,
  setRulesToRemove,
  rulesToRemove,
  scope = "rules",
  promotion,
  formType = "create"
}) => {
  const initialRulesSet = useRef(false);
  const { t } = useTranslation2();
  const direction = useDocumentDirection();
  const formData = form.getValues();
  const { attributes } = usePromotionRuleAttributes(
    ruleType,
    formData.type,
    formData.application_method?.target_type
  );
  const { fields, append, remove, update, replace } = useFieldArray({
    control: form.control,
    name: scope,
    keyName: scope
  });
  const promotionType = useWatch2({
    control: form.control,
    name: "type",
    defaultValue: promotion?.type
  });
  const applicationMethodType = useWatch2({
    control: form.control,
    name: "application_method.type",
    defaultValue: promotion?.application_method?.type
  });
  const applicationMethodTargetType = useWatch2({
    control: form.control,
    name: "application_method.target_type",
    defaultValue: promotion?.application_method?.target_type
  });
  const query = promotionType ? {
    promotion_type: promotionType,
    application_method_type: applicationMethodType,
    application_method_target_type: applicationMethodTargetType
  } : {};
  const { rules, isLoading } = usePromotionRules(promotion?.id || null, ruleType, query, {
    enabled: !!promotion?.id || !!promotionType && !!applicationMethodType
  });
  useEffect2(() => {
    if (isLoading) {
      return;
    }
    if (!fields.length && formType === "edit" && initialRulesSet.current) {
      return;
    }
    if (ruleType === "rules" && !fields.length) {
      form.resetField("rules");
      replace(generateRuleAttributes(rules));
    }
    if (ruleType === "buy-rules" && !fields.length) {
      form.resetField("application_method.buy_rules");
      const rulesToAppend = promotion?.id || promotionType === "standard" ? rules : [...rules, requiredProductRule];
      replace(generateRuleAttributes(rulesToAppend));
    }
    if (ruleType === "target-rules" && !fields.length) {
      form.resetField("application_method.target_rules");
      const rulesToAppend = promotion?.id || promotionType === "standard" ? rules : [...rules, requiredProductRule];
      replace(generateRuleAttributes(rulesToAppend));
    }
    initialRulesSet.current = true;
  }, [
    promotionType,
    isLoading,
    ruleType,
    fields.length,
    formType,
    form,
    replace,
    rules,
    promotion?.id
  ]);
  return /* @__PURE__ */ jsxs2(
    "div",
    {
      className: "flex flex-col",
      "data-testid": `rules-form-field-${ruleType}`,
      children: [
        /* @__PURE__ */ jsx2(
          Heading,
          {
            level: "h2",
            className: "mb-2",
            "data-testid": `rules-form-field-heading-${ruleType}`,
            children: t(
              ruleType === "target-rules" ? `promotions.fields.conditions.${ruleType}.${applicationMethodTargetType}.title` : `promotions.fields.conditions.${ruleType}.title`
            )
          }
        ),
        /* @__PURE__ */ jsx2(
          Text,
          {
            className: "txt-small mb-6 text-ui-fg-subtle",
            "data-testid": `rules-form-field-description-${ruleType}`,
            children: t(
              ruleType === "target-rules" ? `promotions.fields.conditions.${ruleType}.${applicationMethodTargetType}.description` : `promotions.fields.conditions.${ruleType}.description`
            )
          }
        ),
        fields.map((fieldRule, index) => {
          const identifier = fieldRule.id;
          return /* @__PURE__ */ jsxs2(Fragment, { children: [
            /* @__PURE__ */ jsxs2(
              "div",
              {
                className: "flex flex-row gap-2 rounded-xl border border-ui-border-base bg-ui-bg-subtle px-2 py-2",
                "data-testid": `rules-form-field-rule-${ruleType}-${index}`,
                children: [
                  /* @__PURE__ */ jsxs2("div", { className: "grow", children: [
                    /* @__PURE__ */ jsx2(
                      Form.Field,
                      {
                        name: `${scope}.${index}.attribute`,
                        render: ({ field }) => {
                          const { onChange, ref, ...fieldProps } = field;
                          const existingAttributes = fields?.map((field2) => field2.attribute) || [];
                          const attributeOptions = attributes?.filter((attr) => {
                            if (attr.value === fieldRule.attribute) {
                              return true;
                            }
                            return !existingAttributes.includes(attr.value);
                          }) || [];
                          const disabled = !!fieldRule.required;
                          const onValueChange = (e) => {
                            const currentAttributeOption = attributeOptions.find((ao) => ao.id === e);
                            const fieldRuleOverrides = {
                              ...fieldRule,
                              disguised: currentAttributeOption?.disguised || false
                            };
                            if (currentAttributeOption?.operators?.length === 1) {
                              fieldRuleOverrides.operator = currentAttributeOption.operators[0].value;
                            }
                            if (fieldRuleOverrides.operator === "eq") {
                              fieldRuleOverrides.values = "";
                            } else {
                              fieldRuleOverrides.values = [];
                            }
                            update(index, fieldRuleOverrides);
                            onChange(e);
                          };
                          return /* @__PURE__ */ jsxs2(
                            Form.Item,
                            {
                              className: "mb-2",
                              "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-item`,
                              children: [
                                fieldRule.required && /* @__PURE__ */ jsx2(
                                  "div",
                                  {
                                    className: "flex items-center px-2",
                                    "data-testid": `rules-form-field-rule-${ruleType}-${index}-required-label`,
                                    children: /* @__PURE__ */ jsx2("p", { className: "text txt-small text-ui-fg-muted", children: t("promotions.form.required") })
                                  }
                                ),
                                /* @__PURE__ */ jsx2(
                                  Form.Control,
                                  {
                                    "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-control`,
                                    children: !disabled ? /* @__PURE__ */ jsxs2(
                                      Select,
                                      {
                                        dir: direction,
                                        ...fieldProps,
                                        onValueChange,
                                        disabled: fieldRule.required,
                                        "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-select`,
                                        children: [
                                          /* @__PURE__ */ jsx2(
                                            Select.Trigger,
                                            {
                                              ref,
                                              className: "bg-ui-bg-base",
                                              "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-select-trigger`,
                                              children: /* @__PURE__ */ jsx2(Select.Value, { placeholder: t("promotions.form.selectAttribute") })
                                            }
                                          ),
                                          /* @__PURE__ */ jsx2(
                                            Select.Content,
                                            {
                                              "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-select-content`,
                                              children: attributeOptions?.map((c, i) => /* @__PURE__ */ jsx2(
                                                Select.Item,
                                                {
                                                  value: c.value,
                                                  "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-select-option-${c.value}`,
                                                  children: /* @__PURE__ */ jsx2("span", { className: "text-ui-fg-subtle", children: c.label })
                                                },
                                                `${identifier}-attribute-option-${i}`
                                              ))
                                            }
                                          )
                                        ]
                                      }
                                    ) : /* @__PURE__ */ jsx2(
                                      DisabledField,
                                      {
                                        label: attributeOptions?.find((ao) => ao.value === fieldRule.attribute)?.label || "",
                                        field
                                      }
                                    )
                                  }
                                ),
                                /* @__PURE__ */ jsx2(
                                  Form.ErrorMessage,
                                  {
                                    "data-testid": `rules-form-field-rule-${ruleType}-${index}-attribute-error`
                                  }
                                )
                              ]
                            }
                          );
                        }
                      }
                    ),
                    /* @__PURE__ */ jsxs2("div", { className: "flex gap-2", children: [
                      /* @__PURE__ */ jsx2(
                        Form.Field,
                        {
                          name: `${scope}.${index}.operator`,
                          render: ({ field }) => {
                            const { onChange, ref, ...fieldProps } = field;
                            const currentAttributeOption = attributes?.find(
                              (attr) => attr.value === fieldRule.attribute
                            );
                            const options = currentAttributeOption?.operators?.map((o, idx) => ({
                              label: o.label,
                              value: o.value,
                              key: `${identifier}-operator-option-${idx}`
                            })) || [];
                            const disabled = !!fieldRule.attribute && options?.length <= 1;
                            return /* @__PURE__ */ jsxs2(
                              Form.Item,
                              {
                                className: "basis-1/2",
                                "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-item`,
                                children: [
                                  /* @__PURE__ */ jsx2(
                                    Form.Control,
                                    {
                                      "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-control`,
                                      children: !disabled ? /* @__PURE__ */ jsxs2(
                                        Select,
                                        {
                                          dir: direction,
                                          ...fieldProps,
                                          disabled: !fieldRule.attribute,
                                          onValueChange: onChange,
                                          "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-select`,
                                          children: [
                                            /* @__PURE__ */ jsx2(
                                              Select.Trigger,
                                              {
                                                ref,
                                                className: "bg-ui-bg-base",
                                                "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-select-trigger`,
                                                children: /* @__PURE__ */ jsx2(Select.Value, { placeholder: "Select Operator" })
                                              }
                                            ),
                                            /* @__PURE__ */ jsx2(
                                              Select.Content,
                                              {
                                                "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-select-content`,
                                                children: options?.map((c) => /* @__PURE__ */ jsx2(
                                                  Select.Item,
                                                  {
                                                    value: c.value,
                                                    "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-select-option-${c.value}`,
                                                    children: /* @__PURE__ */ jsx2("span", { className: "text-ui-fg-subtle", children: c.label })
                                                  },
                                                  c.key
                                                ))
                                              }
                                            )
                                          ]
                                        }
                                      ) : /* @__PURE__ */ jsx2(
                                        DisabledField,
                                        {
                                          label: options.find((o) => o.value === fieldProps.value)?.label || "",
                                          field
                                        }
                                      )
                                    }
                                  ),
                                  /* @__PURE__ */ jsx2(
                                    Form.ErrorMessage,
                                    {
                                      "data-testid": `rules-form-field-rule-${ruleType}-${index}-operator-error`
                                    }
                                  )
                                ]
                              }
                            );
                          }
                        }
                      ),
                      /* @__PURE__ */ jsx2(
                        RuleValueFormField,
                        {
                          form,
                          identifier,
                          scope,
                          name: `${scope}.${index}.values`,
                          operator: `${scope}.${index}.operator`,
                          fieldRule,
                          attributes,
                          ruleType,
                          applicationMethodTargetType
                        }
                      )
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx2("div", { className: "size-7 flex-none self-center", children: !fieldRule.required && /* @__PURE__ */ jsx2(
                    IconButton,
                    {
                      size: "small",
                      variant: "transparent",
                      className: "text-ui-fg-muted",
                      type: "button",
                      onClick: () => {
                        if (!fieldRule.required) {
                          setRulesToRemove && setRulesToRemove([...rulesToRemove, fieldRule]);
                          remove(index);
                        }
                      },
                      "data-testid": `rules-form-field-rule-${ruleType}-${index}-remove-button`,
                      children: /* @__PURE__ */ jsx2(XMarkMini, {})
                    }
                  ) })
                ]
              }
            ),
            index < fields.length - 1 && /* @__PURE__ */ jsxs2(
              "div",
              {
                className: "relative px-6 py-3",
                "data-testid": `rules-form-field-rule-${ruleType}-${index}-separator`,
                children: [
                  /* @__PURE__ */ jsx2("div", { className: "absolute bottom-0 left-[40px] top-0 z-[-1] w-px border-ui-border-strong bg-[linear-gradient(var(--border-strong)_33%,rgba(255,255,255,0)_0%)] bg-[length:1px_3px] bg-repeat-y" }),
                  /* @__PURE__ */ jsx2(
                    Badge,
                    {
                      size: "2xsmall",
                      className: "text-xs",
                      "data-testid": `rules-form-field-rule-${ruleType}-${index}-and-badge`,
                      children: t("promotions.form.and")
                    }
                  )
                ]
              }
            )
          ] }, `${fieldRule.id}.${index}.${fieldRule.attribute}`);
        }),
        /* @__PURE__ */ jsxs2(
          "div",
          {
            className: fields.length ? "mt-6" : "",
            "data-testid": `rules-form-field-actions-${ruleType}`,
            children: [
              /* @__PURE__ */ jsx2(
                Button,
                {
                  type: "button",
                  variant: "secondary",
                  className: "inline-block",
                  disabled: fields.length === attributes?.length,
                  onClick: () => {
                    append({
                      attribute: "",
                      operator: "",
                      values: [],
                      required: false
                    });
                  },
                  "data-testid": `rules-form-field-add-condition-button-${ruleType}`,
                  children: t("promotions.fields.addCondition")
                }
              ),
              !!fields.length && /* @__PURE__ */ jsx2(
                Button,
                {
                  type: "button",
                  variant: "transparent",
                  className: "ml-2 inline-block text-ui-fg-muted hover:text-ui-fg-subtle",
                  onClick: () => {
                    const indicesToRemove = fields.map((field, index) => field.required ? null : index).filter((f) => f !== null);
                    setRulesToRemove && setRulesToRemove(fields.filter((field) => !field.required));
                    remove(indicesToRemove);
                  },
                  "data-testid": `rules-form-field-clear-all-button-${ruleType}`,
                  children: t("promotions.fields.clearAll")
                }
              )
            ]
          }
        )
      ]
    }
  );
};
var DisabledField = forwardRef(
  ({ label, field }, ref) => {
    return /* @__PURE__ */ jsxs2("div", { children: [
      /* @__PURE__ */ jsx2("div", { className: "txt-compact-small h-8 rounded-md bg-ui-bg-component px-2 py-1.5 text-ui-fg-base shadow-borders-base", children: label }),
      /* @__PURE__ */ jsx2(
        "input",
        {
          ...field,
          ref,
          disabled: true,
          hidden: true
        }
      )
    ] });
  }
);
DisabledField.displayName = "DisabledField";

export {
  RulesFormField
};
