import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  formatCurrency
} from "./chunk-XSX255FK.js";
import {
  getPaymentsFromOrder
} from "./chunk-3KOTDGC2.js";
import {
  DEFAULT_FIELDS
} from "./chunk-Y2M536WR.js";
import {
  getLocaleAmount
} from "./chunk-PXYDR7WQ.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.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 {
  useRefundPayment,
  useRefundReasons
} from "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import "./chunk-O4STPJR2.js";
import {
  useOrder
} from "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/orders/order-create-refund/order-create-refund.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/orders/order-create-refund/components/create-refund-form/create-refund-form.tsx
import { useEffect, useMemo, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  CurrencyInput,
  Heading,
  Label,
  Select,
  Textarea,
  toast
} from "@medusajs/ui";
import { formatValue } from "react-currency-input-field";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var CreateRefundSchema = zod.object({
  amount: zod.object({
    value: zod.string().or(zod.number()),
    float: zod.number().or(zod.null())
  }),
  note: zod.string().optional(),
  refund_reason_id: zod.string().optional()
});
var CreateRefundForm = ({ order }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { refund_reasons } = useRefundReasons();
  const [searchParams] = useSearchParams();
  const hasPaymentIdInSearchParams = !!searchParams.get("paymentId");
  const [paymentId, setPaymentId] = useState(
    searchParams.get("paymentId") || void 0
  );
  const payments = getPaymentsFromOrder(order);
  const payment = payments.find((p) => p.id === paymentId);
  const paymentAmount = payment?.amount || 0;
  const currency = useMemo(
    () => currencies[order.currency_code.toUpperCase()],
    [order.currency_code]
  );
  const direction = useDocumentDirection();
  const form = useForm({
    defaultValues: {
      amount: {
        value: paymentAmount.toFixed(currency.decimal_digits),
        float: paymentAmount
      }
    },
    resolver: zodResolver(CreateRefundSchema)
  });
  useEffect(() => {
    const pendingDifference = order.summary.pending_difference;
    const paymentAmount2 = payment?.amount || 0;
    const pendingAmount = pendingDifference < 0 ? Math.min(Math.abs(pendingDifference), paymentAmount2) : paymentAmount2;
    const normalizedAmount = pendingAmount < 0 ? pendingAmount * -1 : pendingAmount;
    form.setValue("amount", {
      value: normalizedAmount.toFixed(currency.decimal_digits),
      float: normalizedAmount
    });
  }, [payment?.id || ""]);
  const { mutateAsync, isPending } = useRefundPayment(order.id, payment?.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    await mutateAsync(
      {
        amount: data.amount.float,
        note: data.note,
        refund_reason_id: data.refund_reason_id
      },
      {
        onSuccess: () => {
          toast.success(
            t("orders.payment.refundPaymentSuccess", {
              amount: formatCurrency(
                data.amount.float,
                payment?.currency_code
              )
            })
          );
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "order-create-refund-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex size-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(
          RouteDrawer.Body,
          {
            className: "flex-1 overflow-auto",
            "data-testid": "order-create-refund-body",
            children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-6", children: [
              !hasPaymentIdInSearchParams && /* @__PURE__ */ jsxs(
                Select,
                {
                  dir: direction,
                  value: paymentId,
                  onValueChange: (value) => {
                    setPaymentId(value);
                  },
                  "data-testid": "order-create-refund-payment-select",
                  children: [
                    /* @__PURE__ */ jsx(
                      Label,
                      {
                        className: "txt-compact-small -mb-4 font-sans font-medium",
                        "data-testid": "order-create-refund-payment-label",
                        children: t("orders.payment.selectPaymentToRefund")
                      }
                    ),
                    /* @__PURE__ */ jsx(Select.Trigger, { "data-testid": "order-create-refund-payment-trigger", children: /* @__PURE__ */ jsx(
                      Select.Value,
                      {
                        placeholder: t("orders.payment.selectPaymentToRefund")
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Select.Content, { "data-testid": "order-create-refund-payment-content", children: payments.map((payment2) => {
                      const totalRefunded = payment2.refunds?.reduce(
                        (acc, next) => next.amount + acc,
                        0
                      ) || 0;
                      return /* @__PURE__ */ jsxs(
                        Select.Item,
                        {
                          value: payment2.id,
                          disabled: !!payment2.canceled_at || totalRefunded >= payment2.amount,
                          className: "flex items-center justify-center",
                          "data-testid": `order-create-refund-payment-option-${payment2.id}`,
                          children: [
                            /* @__PURE__ */ jsxs("span", { children: [
                              getLocaleAmount(
                                payment2.amount,
                                payment2.currency_code
                              ),
                              " - "
                            ] }),
                            /* @__PURE__ */ jsx("span", { children: formatProvider(payment2.provider_id) }),
                            /* @__PURE__ */ jsxs("span", { children: [
                              " - (#",
                              payment2.id.substring(23),
                              ")"
                            ] })
                          ]
                        },
                        payment2.id
                      );
                    }) })
                  ]
                }
              ),
              hasPaymentIdInSearchParams && /* @__PURE__ */ jsxs(
                Heading,
                {
                  level: "h2",
                  "data-testid": "order-create-refund-payment-display",
                  children: [
                    getLocaleAmount(
                      payment.amount,
                      payment.currency_code
                    ),
                    " ",
                    "- (#",
                    payment.id.substring(23),
                    ")"
                  ]
                }
              ),
              /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: "amount",
                  rules: {
                    required: true,
                    min: 0,
                    max: paymentAmount
                  },
                  render: ({ field: { onChange, ...field } }) => {
                    return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "order-create-refund-amount-item", children: [
                      /* @__PURE__ */ jsx(Form.Label, { "data-testid": "order-create-refund-amount-label", children: t("fields.amount") }),
                      /* @__PURE__ */ jsx(Form.Control, { "data-testid": "order-create-refund-amount-control", children: /* @__PURE__ */ jsx(
                        CurrencyInput,
                        {
                          ...field,
                          min: 0,
                          placeholder: formatValue({
                            value: "0",
                            decimalScale: currency.decimal_digits
                          }),
                          decimalScale: currency.decimal_digits,
                          symbol: currency.symbol_native,
                          code: currency.code,
                          value: field.value.value,
                          onValueChange: (_value, _name, values) => onChange({
                            value: values?.value ?? "",
                            float: values?.float ?? null
                          }),
                          autoFocus: true,
                          "data-testid": "order-create-refund-amount-input"
                        }
                      ) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "order-create-refund-amount-error" })
                    ] });
                  }
                }
              ),
              /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: "refund_reason_id",
                  render: ({ field }) => {
                    return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "order-create-refund-reason-item", children: [
                      /* @__PURE__ */ jsx(
                        Form.Label,
                        {
                          "data-testid": "order-create-refund-reason-label",
                          optional: true,
                          children: t("fields.refundReason")
                        }
                      ),
                      /* @__PURE__ */ jsx(Form.Control, { "data-testid": "order-create-refund-reason-control", children: /* @__PURE__ */ jsxs(
                        Select,
                        {
                          dir: direction,
                          value: field.value,
                          onValueChange: field.onChange,
                          "data-testid": "order-create-refund-reason-select",
                          children: [
                            /* @__PURE__ */ jsx(Select.Trigger, { "data-testid": "order-create-refund-reason-trigger", children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                            /* @__PURE__ */ jsx(Select.Content, { "data-testid": "order-create-refund-reason-content", children: refund_reasons?.map(
                              (reason) => /* @__PURE__ */ jsx(
                                Select.Item,
                                {
                                  value: reason.id,
                                  "data-testid": `order-create-refund-reason-option-${reason.id}`,
                                  children: reason.label
                                },
                                reason.id
                              )
                            ) })
                          ]
                        }
                      ) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "order-create-refund-reason-error" })
                    ] });
                  }
                }
              ),
              /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: `note`,
                  render: ({ field }) => {
                    return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "order-create-refund-note-item", children: [
                      /* @__PURE__ */ jsx(
                        Form.Label,
                        {
                          "data-testid": "order-create-refund-note-label",
                          optional: true,
                          children: t("fields.note")
                        }
                      ),
                      /* @__PURE__ */ jsx(Form.Control, { "data-testid": "order-create-refund-note-control", children: /* @__PURE__ */ jsx(
                        Textarea,
                        {
                          ...field,
                          "data-testid": "order-create-refund-note-input"
                        }
                      ) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "order-create-refund-note-error" })
                    ] });
                  }
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { "data-testid": "order-create-refund-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,
            {
              variant: "secondary",
              size: "small",
              "data-testid": "order-create-refund-cancel-button",
              children: t("actions.cancel")
            }
          ) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              isLoading: isPending,
              type: "submit",
              variant: "primary",
              size: "small",
              disabled: !!Object.keys(form.formState.errors || {}).length,
              "data-testid": "order-create-refund-save-button",
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};

// src/pages/orders/order-create-refund/order-create-refund.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var OrderCreateRefund = () => {
  const { t } = useTranslation2();
  const params = useParams();
  const { order } = useOrder(params.id, {
    fields: DEFAULT_FIELDS
  });
  return /* @__PURE__ */ jsxs2(RouteDrawer, { "data-testid": "order-create-refund-drawer", children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { "data-testid": "order-create-refund-header", children: /* @__PURE__ */ jsx2(Heading2, { "data-testid": "order-create-refund-heading", children: t("orders.payment.createRefund") }) }),
    order && /* @__PURE__ */ jsx2(CreateRefundForm, { order })
  ] });
};
export {
  OrderCreateRefund as Component
};
