import {
  DeprecatedPercentageInput
} from "./chunk-MAEP2UCK.js";
import {
  currencies,
  getCurrencySymbol
} from "./chunk-IQPN4PZJ.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  usePromotion,
  useUpdatePromotion
} from "./chunk-HAFZQK53.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, CurrencyInput, Input, RadioGroup, Text } from "@medusajs/ui";
import { useForm, useWatch } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
import { useEffect } from "react";
import * as zod from "zod";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var EditPromotionSchema = zod.object({
  is_automatic: zod.string().toLowerCase(),
  code: zod.string().min(1),
  is_tax_inclusive: zod.boolean().optional(),
  status: zod.enum(["active", "inactive", "draft"]),
  value_type: zod.enum(["fixed", "percentage"]),
  value: zod.number().min(0).or(zod.string().min(1)),
  allocation: zod.enum(["each", "across", "once"]),
  max_quantity: zod.number().optional().nullable(),
  target_type: zod.enum(["order", "shipping_methods", "items"])
}).refine(
  (data) => {
    if (data.allocation === "across") {
      return true;
    }
    return typeof data.max_quantity === "number";
  },
  {
    path: ["max_quantity"],
    message: `required field`
  }
);
var EditPromotionDetailsForm = ({
  promotion
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const allocationRaw = promotion.application_method?.allocation;
  const allocationDefault = allocationRaw === "once" ? "once" : allocationRaw === "across" ? "across" : "each";
  const form = useForm({
    defaultValues: {
      is_automatic: promotion.is_automatic.toString(),
      is_tax_inclusive: promotion.is_tax_inclusive,
      code: promotion.code,
      status: promotion.status,
      value: promotion.application_method.value,
      allocation: allocationDefault,
      max_quantity: promotion.application_method?.max_quantity ?? null,
      value_type: promotion.application_method.type,
      target_type: promotion.application_method.target_type
    },
    resolver: zodResolver(EditPromotionSchema)
  });
  const watchValueType = useWatch({
    control: form.control,
    name: "value_type"
  });
  const watchAllocation = useWatch({
    control: form.control,
    name: "allocation"
  });
  const isFixedValueType = watchValueType === "fixed";
  const { mutateAsync, isPending } = useUpdatePromotion(promotion.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    const value = typeof data.value === "number" ? data.value : parseFloat(data.value);
    if (isNaN(value) || value < 0) {
      form.setError("value", { message: t("promotions.form.value.invalid") });
      return;
    }
    await mutateAsync(
      {
        is_automatic: data.is_automatic === "true",
        code: data.code,
        status: data.status,
        is_tax_inclusive: data.is_tax_inclusive,
        application_method: {
          value,
          type: data.value_type,
          allocation: data.allocation,
          max_quantity: data.max_quantity ?? null
        }
      },
      {
        onSuccess: () => {
          handleSuccess();
        }
      }
    );
  });
  const allocationWatchValue = useWatch({
    control: form.control,
    name: "value_type"
  });
  useEffect(() => {
    if (!(allocationWatchValue === "fixed" && promotion.type === "standard")) {
      form.setValue("is_tax_inclusive", false);
    }
  }, [allocationWatchValue, form, promotion]);
  useEffect(() => {
    if (watchAllocation === "once" && !form.getValues("max_quantity")) {
      form.setValue("max_quantity", 1);
    }
  }, [watchAllocation, form]);
  const direction = useDocumentDirection();
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "promotion-edit-details-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-8 overflow-y-auto", "data-testid": "promotion-edit-details-form-body", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-8", children: [
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "status",
              render: ({ field }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-status-item", children: [
                  /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-status-label", children: t("promotions.form.status.label") }),
                  /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-status-control", children: /* @__PURE__ */ jsxs(
                    RadioGroup,
                    {
                      dir: direction,
                      className: "flex-col gap-y-3",
                      ...field,
                      value: field.value,
                      onValueChange: field.onChange,
                      "data-testid": "promotion-edit-details-form-status-radio-group",
                      children: [
                        /* @__PURE__ */ jsx(
                          RadioGroup.ChoiceBox,
                          {
                            value: "draft",
                            label: t("promotions.form.status.draft.title"),
                            description: t(
                              "promotions.form.status.draft.description"
                            ),
                            "data-testid": "promotion-edit-details-form-status-option-draft"
                          }
                        ),
                        /* @__PURE__ */ jsx(
                          RadioGroup.ChoiceBox,
                          {
                            value: "active",
                            label: t("promotions.form.status.active.title"),
                            description: t(
                              "promotions.form.status.active.description"
                            ),
                            "data-testid": "promotion-edit-details-form-status-option-active"
                          }
                        ),
                        /* @__PURE__ */ jsx(
                          RadioGroup.ChoiceBox,
                          {
                            value: "inactive",
                            label: t("promotions.form.status.inactive.title"),
                            description: t(
                              "promotions.form.status.inactive.description"
                            ),
                            "data-testid": "promotion-edit-details-form-status-option-inactive"
                          }
                        )
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-status-error" })
                ] });
              }
            }
          ),
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "is_automatic",
              render: ({ field }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-method-item", children: [
                  /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-method-label", children: t("promotions.form.method.label") }),
                  /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-method-control", children: /* @__PURE__ */ jsxs(
                    RadioGroup,
                    {
                      dir: direction,
                      className: "flex-col gap-y-3",
                      ...field,
                      value: field.value,
                      onValueChange: field.onChange,
                      "data-testid": "promotion-edit-details-form-method-radio-group",
                      children: [
                        /* @__PURE__ */ jsx(
                          RadioGroup.ChoiceBox,
                          {
                            value: "false",
                            label: t("promotions.form.method.code.title"),
                            description: t(
                              "promotions.form.method.code.description"
                            ),
                            "data-testid": "promotion-edit-details-form-method-option-code"
                          }
                        ),
                        /* @__PURE__ */ jsx(
                          RadioGroup.ChoiceBox,
                          {
                            value: "true",
                            label: t("promotions.form.method.automatic.title"),
                            description: t(
                              "promotions.form.method.automatic.description"
                            ),
                            "data-testid": "promotion-edit-details-form-method-option-automatic"
                          }
                        )
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-method-error" })
                ] });
              }
            }
          ),
          allocationWatchValue === "fixed" && promotion.type === "standard" && /* @__PURE__ */ jsx(
            SwitchBox,
            {
              control: form.control,
              name: "is_tax_inclusive",
              label: t("promotions.form.taxInclusive.title"),
              description: t("promotions.form.taxInclusive.description")
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "code",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-code-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-code-label", children: t("promotions.form.code.title") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-code-control", children: /* @__PURE__ */ jsx(Input, { ...field, "data-testid": "promotion-edit-details-form-code-input" }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-code-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: /* @__PURE__ */ jsx(
                  Trans,
                  {
                    t,
                    i18nKey: "promotions.form.code.description",
                    components: [/* @__PURE__ */ jsx("br", {}, "break")]
                  }
                )
              }
            )
          ] }),
          promotion.application_method?.target_type !== "shipping_methods" && /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "value_type",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-value-type-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-value-type-label", children: t("promotions.fields.value_type") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-value-type-control", children: /* @__PURE__ */ jsxs(
                      RadioGroup,
                      {
                        dir: direction,
                        className: "flex-col gap-y-3",
                        ...field,
                        onValueChange: field.onChange,
                        "data-testid": "promotion-edit-details-form-value-type-radio-group",
                        children: [
                          /* @__PURE__ */ jsx(
                            RadioGroup.ChoiceBox,
                            {
                              value: "fixed",
                              label: t(
                                "promotions.form.value_type.fixed.title"
                              ),
                              description: t(
                                "promotions.form.value_type.fixed.description"
                              ),
                              "data-testid": "promotion-edit-details-form-value-type-option-fixed"
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            RadioGroup.ChoiceBox,
                            {
                              value: "percentage",
                              label: t(
                                "promotions.form.value_type.percentage.title"
                              ),
                              description: t(
                                "promotions.form.value_type.percentage.description"
                              ),
                              "data-testid": "promotion-edit-details-form-value-type-option-percentage"
                            }
                          )
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-value-type-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "value",
                render: ({ field: { onChange, ...field } }) => {
                  const currencyCode = promotion.application_method?.currency_code ?? "USD";
                  const currencyInfo = currencies[currencyCode?.toUpperCase() || "USD"];
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-value-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-value-label", children: isFixedValueType ? t("fields.amount") : t("fields.percentage") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-value-control", children: isFixedValueType ? /* @__PURE__ */ jsx(
                      CurrencyInput,
                      {
                        min: 0,
                        onValueChange: (val) => onChange(val),
                        decimalSeparator: ".",
                        groupSeparator: ",",
                        decimalScale: currencyInfo.decimal_digits,
                        decimalsLimit: currencyInfo.decimal_digits,
                        code: currencyCode,
                        symbol: getCurrencySymbol(currencyCode),
                        ...field,
                        value: field.value,
                        "data-testid": "promotion-edit-details-form-value-currency-input"
                      }
                    ) : /* @__PURE__ */ jsx(
                      DeprecatedPercentageInput,
                      {
                        min: 0,
                        max: 100,
                        ...field,
                        value: field.value || "",
                        onChange: (e) => {
                          onChange(
                            e.target.value === "" ? null : parseFloat(e.target.value)
                          );
                        },
                        "data-testid": "promotion-edit-details-form-value-percentage-input"
                      },
                      "amount"
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-value-error" })
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "allocation",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-allocation-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-allocation-label", children: t("promotions.fields.allocation") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-allocation-control", children: /* @__PURE__ */ jsxs(
                      RadioGroup,
                      {
                        dir: direction,
                        className: "flex-col gap-y-3",
                        ...field,
                        onValueChange: field.onChange,
                        "data-testid": "promotion-edit-details-form-allocation-radio-group",
                        children: [
                          /* @__PURE__ */ jsx(
                            RadioGroup.ChoiceBox,
                            {
                              value: "each",
                              label: t("promotions.form.allocation.each.title"),
                              description: t(
                                "promotions.form.allocation.each.description"
                              ),
                              "data-testid": "promotion-edit-details-form-allocation-option-each"
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            RadioGroup.ChoiceBox,
                            {
                              value: "once",
                              label: t("promotions.form.allocation.once.title", {
                                defaultValue: "Once"
                              }),
                              description: t(
                                "promotions.form.allocation.once.description",
                                { defaultValue: "Limit discount to max quantity" }
                              ),
                              "data-testid": "promotion-edit-details-form-allocation-option-once"
                            }
                          )
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-allocation-error" })
                  ] });
                }
              }
            ),
            (watchAllocation === "each" || watchAllocation === "once") && /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "max_quantity",
                render: () => {
                  return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-edit-details-form-max-quantity-item", children: [
                    /* @__PURE__ */ jsx(Form.Label, { "data-testid": "promotion-edit-details-form-max-quantity-label", children: t("promotions.form.max_quantity.title") }),
                    /* @__PURE__ */ jsx(Form.Control, { "data-testid": "promotion-edit-details-form-max-quantity-control", children: /* @__PURE__ */ jsx(
                      Input,
                      {
                        ...form.register("max_quantity", {
                          valueAsNumber: true
                        }),
                        type: "number",
                        min: 1,
                        placeholder: "3",
                        "data-testid": "promotion-edit-details-form-max-quantity-input"
                      }
                    ) }),
                    /* @__PURE__ */ jsx(
                      Text,
                      {
                        size: "small",
                        leading: "compact",
                        className: "text-ui-fg-subtle",
                        "data-testid": "promotion-edit-details-form-max-quantity-description",
                        children: /* @__PURE__ */ jsx(
                          Trans,
                          {
                            t,
                            i18nKey: "promotions.form.max_quantity.description",
                            components: [/* @__PURE__ */ jsx("br", {}, "break")]
                          }
                        )
                      }
                    ),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "promotion-edit-details-form-max-quantity-error" })
                  ] });
                }
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { "data-testid": "promotion-edit-details-form-footer", 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", "data-testid": "promotion-edit-details-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, "data-testid": "promotion-edit-details-form-save-button", children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var PromotionEditDetails = () => {
  const { id } = useParams();
  const { t } = useTranslation2();
  const { promotion, isLoading, isError, error } = usePromotion(id);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(Heading, { children: t("promotions.edit.title") }) }),
    !isLoading && promotion && /* @__PURE__ */ jsx2(EditPromotionDetailsForm, { promotion })
  ] });
};
export {
  PromotionEditDetails as Component
};
