import {
  getLoyaltyPlugin
} from "./chunk-AMRS4CSX.mjs";
import {
  formatProvider
} from "./chunk-IR5DHEKS.mjs";
import {
  formatCurrency
} from "./chunk-WATKBUHQ.mjs";
import {
  getPaymentsFromOrder
} from "./chunk-4XSXVVYD.mjs";
import {
  DEFAULT_FIELDS
} from "./chunk-C7F7MMXS.mjs";
import {
  getLocaleAmount
} from "./chunk-X6BAAGCL.mjs";
import {
  currencies
} from "./chunk-DK4WIVY6.mjs";
import "./chunk-IUCDCPJU.mjs";
import {
  KeyboundForm
} from "./chunk-6HTZNHPT.mjs";
import {
  RouteDrawer
} from "./chunk-OV6YUU3D.mjs";
import {
  useRouteModal
} from "./chunk-ULMMKZ3U.mjs";
import {
  useDocumentDirection
} from "./chunk-S4DMV3ZT.mjs";
import {
  Form
} from "./chunk-OBQI23QM.mjs";
import {
  usePlugins,
  useRefundPayment,
  useRefundReasons
} from "./chunk-OW2UL5FI.mjs";
import "./chunk-5DUV4AET.mjs";
import "./chunk-FAB3VINY.mjs";
import "./chunk-Q7YBE4IP.mjs";
import "./chunk-HI6URQ7H.mjs";
import "./chunk-6CLQKVAU.mjs";
import "./chunk-KI7TOXBR.mjs";
import "./chunk-QBIQEVTU.mjs";
import "./chunk-WAXMT4IY.mjs";
import "./chunk-DYDGGABK.mjs";
import "./chunk-LGNTHZ5Y.mjs";
import "./chunk-CN7JXSGW.mjs";
import "./chunk-AO2USOOE.mjs";
import "./chunk-KWWLGCSY.mjs";
import "./chunk-5AFMB7XQ.mjs";
import "./chunk-5U6AZEO7.mjs";
import "./chunk-A63RZVX6.mjs";
import "./chunk-HBXV7ENS.mjs";
import {
  useCreateOrderCreditLine,
  useOrder
} from "./chunk-ZBMENGLV.mjs";
import "./chunk-LGLPAUIO.mjs";
import "./chunk-CDORR33H.mjs";
import "./chunk-DE44HCDH.mjs";
import "./chunk-MUOBXNL6.mjs";
import "./chunk-BEQ5XTWH.mjs";
import "./chunk-HP2JH45P.mjs";
import "./chunk-VCSSQVPD.mjs";
import "./chunk-SQDIZZDW.mjs";
import "./chunk-LA2ILUXH.mjs";
import "./chunk-7AXHHXCX.mjs";
import "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

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

// src/routes/orders/order-balance-settlement/components/order-balance-settlement-form/order-balance-settlement-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  clx,
  CurrencyInput,
  Divider,
  Label,
  RadioGroup,
  Select,
  Textarea,
  toast
} from "@medusajs/ui";
import { useEffect, useMemo, useState } from "react";
import { formatValue } from "react-currency-input-field";
import { useForm } from "react-hook-form";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var OrderBalanceSettlementSchema = zod.object({
  settlement_type: zod.enum(["credit_line", "refund"]),
  refund: zod.object({
    amount: zod.object({
      value: zod.string().or(zod.number()).optional(),
      float: zod.number().or(zod.null())
    }),
    note: zod.string().optional()
  }).optional(),
  credit_line: zod.object({
    amount: zod.object({
      value: zod.string().or(zod.number()).optional(),
      float: zod.number().or(zod.null())
    }),
    note: zod.string().optional()
  }).optional()
});
var OrderBalanceSettlementForm = ({
  order
}) => {
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const { handleSuccess } = useRouteModal();
  const paymentId = searchParams.get("paymentId");
  const payments = getPaymentsFromOrder(order);
  const pendingDifference = order.summary.pending_difference * -1;
  const [activePayment, setActivePayment] = useState(
    paymentId ? payments.find((p) => p.id === paymentId) || null : null
  );
  const form = useForm({
    defaultValues: {
      settlement_type: "refund",
      refund: {
        amount: {
          value: "",
          float: null
        }
      },
      credit_line: {
        amount: {
          value: "",
          float: null
        }
      }
    },
    resolver: zodResolver(OrderBalanceSettlementSchema)
  });
  const { mutateAsync: createCreditLine, isPending: isCreditLinePending } = useCreateOrderCreditLine(order.id);
  const { mutateAsync: createRefund, isPending: isRefundPending } = useRefundPayment(order.id, activePayment?.id);
  const settlementType = form.watch("settlement_type");
  const handleSubmit = form.handleSubmit(async (data) => {
    if (data.settlement_type === "credit_line") {
      if (data.credit_line?.amount.float === null) {
        return;
      }
      await createCreditLine(
        {
          amount: data.credit_line.amount.float * -1,
          reference: "refund",
          reference_id: order.id
        },
        {
          onSuccess: () => {
            toast.success(t("orders.creditLines.createCreditLineSuccess"));
            handleSuccess();
          },
          onError: (error) => {
            toast.error(error.message);
          }
        }
      );
    }
    if (data.settlement_type === "refund") {
      if (data.refund?.amount.float === null) {
        return;
      }
      await createRefund(
        {
          amount: data.refund.amount.float,
          note: data.refund.note
        },
        {
          onSuccess: () => {
            toast.success(
              t("orders.payment.refundPaymentSuccess", {
                amount: formatCurrency(
                  data.refund.amount.float,
                  order.currency_code
                )
              })
            );
            handleSuccess();
          },
          onError: (error) => {
            toast.error(error.message);
          }
        }
      );
    }
  });
  const currency = useMemo(
    () => currencies[order.currency_code.toUpperCase()],
    [order.currency_code]
  );
  useEffect(() => {
    form.clearErrors();
    const _minimum = activePayment?.amount ? Math.min(pendingDifference, activePayment.amount) : pendingDifference;
    const minimum = {
      value: _minimum.toFixed(currency.decimal_digits),
      float: _minimum
    };
    if (settlementType === "refund") {
      form.setValue("refund.amount", minimum);
    }
    if (settlementType === "credit_line") {
      form.setValue("credit_line.amount", minimum);
    }
  }, [settlementType, activePayment, pendingDifference, form, currency]);
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { 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", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(Label, { className: "txt-compact-small font-sans font-medium", children: t("orders.balanceSettlement.settlementType") }),
            /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                className: "flex flex-col gap-y-3",
                value: settlementType,
                onValueChange: (value) => form.setValue("settlement_type", value),
                children: [
                  /* @__PURE__ */ jsx(
                    RadioGroup.ChoiceBox,
                    {
                      value: "refund",
                      description: t(
                        "orders.balanceSettlement.settlementTypes.paymentMethodDescription"
                      ),
                      label: t(
                        "orders.balanceSettlement.settlementTypes.paymentMethod"
                      ),
                      className: clx("basis-1/2")
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    RadioGroup.ChoiceBox,
                    {
                      value: "credit_line",
                      description: t(
                        "orders.balanceSettlement.settlementTypes.creditLineDescription"
                      ),
                      label: t(
                        "orders.balanceSettlement.settlementTypes.creditLine"
                      ),
                      className: clx("basis-1/2")
                    }
                  )
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx(Divider, {}),
          settlementType === "refund" && /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-4", children: /* @__PURE__ */ jsxs(
              Select,
              {
                defaultValue: activePayment?.id,
                onValueChange: (value) => {
                  setActivePayment(payments.find((p) => p.id === value));
                },
                children: [
                  /* @__PURE__ */ jsx(Label, { className: "txt-compact-small mb-[-6px] font-sans font-medium", children: t("orders.payment.selectPaymentToRefund") }),
                  /* @__PURE__ */ jsx(Select.Trigger, { children: /* @__PURE__ */ jsx(
                    Select.Value,
                    {
                      placeholder: t("orders.payment.selectPaymentToRefund")
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Select.Content, { children: payments.map((payment) => {
                    const totalRefunded = payment.refunds?.reduce(
                      (acc, next) => next.amount + acc,
                      0
                    ) ?? 0;
                    return /* @__PURE__ */ jsxs(
                      Select.Item,
                      {
                        value: payment.id,
                        disabled: !!payment.canceled_at || totalRefunded >= payment.amount,
                        children: [
                          /* @__PURE__ */ jsxs("span", { children: [
                            getLocaleAmount(
                              payment.amount,
                              payment.currency_code
                            ),
                            " - "
                          ] }),
                          /* @__PURE__ */ jsx("span", { children: payment.provider_id }),
                          /* @__PURE__ */ jsxs("span", { children: [
                            " - (",
                            payment.id.replace("pay_", ""),
                            ")"
                          ] })
                        ]
                      },
                      payment.id
                    );
                  }) })
                ]
              }
            ) }),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "refund.amount",
                render: ({ field: { onChange, ...field } }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("fields.amount") }),
                    /* @__PURE__ */ jsx(Form.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
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: `refund.note`,
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("fields.note") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Textarea, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            )
          ] }),
          settlementType === "credit_line" && /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "credit_line.amount",
              render: ({ field: { onChange, ...field } }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.amount") }),
                  /* @__PURE__ */ jsx(Form.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
                    }
                  ) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] });
              }
            }
          ) })
        ] }) }),
        /* @__PURE__ */ jsx(RouteDrawer.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", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              isLoading: isCreditLinePending || isRefundPending,
              type: "submit",
              variant: "primary",
              size: "small",
              disabled: !!Object.keys(form.formState.errors || {}).length,
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};

// src/routes/orders/order-create-refund/components/create-refund-form/create-refund-form.tsx
import { zodResolver as zodResolver2 } from "@hookform/resolvers/zod";
import {
  Button as Button2,
  CurrencyInput as CurrencyInput2,
  Label as Label2,
  Select as Select2,
  Textarea as Textarea2,
  toast as toast2
} from "@medusajs/ui";
import { useEffect as useEffect2, useMemo as useMemo2, useState as useState2 } from "react";
import { formatValue as formatValue2 } from "react-currency-input-field";
import { useForm as useForm2 } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useSearchParams as useSearchParams2 } from "react-router-dom";
import * as zod2 from "zod";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CreateRefundSchema = zod2.object({
  amount: zod2.object({
    value: zod2.string().or(zod2.number()),
    float: zod2.number().or(zod2.null())
  }),
  note: zod2.string().optional(),
  refund_reason_id: zod2.string().optional()
});
var CreateRefundForm = ({ order }) => {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const { refund_reasons } = useRefundReasons();
  const [searchParams] = useSearchParams2();
  const hasPaymentIdInSearchParams = !!searchParams.get("paymentId");
  const [paymentId, setPaymentId] = useState2(
    searchParams.get("paymentId") || void 0
  );
  const payments = getPaymentsFromOrder(order);
  const payment = payments.find((p) => p.id === paymentId);
  const paymentAmount = payment?.amount || 0;
  const currency = useMemo2(
    () => currencies[order.currency_code.toUpperCase()],
    [order.currency_code]
  );
  const direction = useDocumentDirection();
  const form = useForm2({
    defaultValues: {
      amount: {
        value: paymentAmount.toFixed(currency.decimal_digits),
        float: paymentAmount
      }
    },
    resolver: zodResolver2(CreateRefundSchema)
  });
  useEffect2(() => {
    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: () => {
          toast2.success(
            t("orders.payment.refundPaymentSuccess", {
              amount: formatCurrency(
                data.amount.float,
                payment?.currency_code
              )
            })
          );
          handleSuccess();
        },
        onError: (error) => {
          toast2.error(error.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx2(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs2(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex size-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx2(RouteDrawer.Body, { className: "flex-1 overflow-auto", children: /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-y-4", children: [
          !hasPaymentIdInSearchParams && /* @__PURE__ */ jsxs2(
            Select2,
            {
              dir: direction,
              value: paymentId,
              onValueChange: (value) => {
                setPaymentId(value);
              },
              children: [
                /* @__PURE__ */ jsx2(Label2, { className: "txt-compact-small mb-[-6px] font-sans font-medium", children: t("orders.payment.selectPaymentToRefund") }),
                /* @__PURE__ */ jsx2(Select2.Trigger, { children: /* @__PURE__ */ jsx2(
                  Select2.Value,
                  {
                    placeholder: t("orders.payment.selectPaymentToRefund")
                  }
                ) }),
                /* @__PURE__ */ jsx2(Select2.Content, { children: payments.map((payment2) => {
                  const totalRefunded = payment2.refunds?.reduce(
                    (acc, next) => next.amount + acc,
                    0
                  ) || 0;
                  return /* @__PURE__ */ jsxs2(
                    Select2.Item,
                    {
                      value: payment2.id,
                      disabled: !!payment2.canceled_at || totalRefunded >= payment2.amount,
                      className: "flex items-center justify-center",
                      children: [
                        /* @__PURE__ */ jsxs2("span", { children: [
                          getLocaleAmount(
                            payment2.amount,
                            payment2.currency_code
                          ),
                          " - "
                        ] }),
                        /* @__PURE__ */ jsx2("span", { children: formatProvider(payment2.provider_id) }),
                        /* @__PURE__ */ jsxs2("span", { children: [
                          " - (#",
                          payment2.id.substring(23),
                          ")"
                        ] })
                      ]
                    },
                    payment2.id
                  );
                }) })
              ]
            }
          ),
          hasPaymentIdInSearchParams && /* @__PURE__ */ jsxs2("div", { className: "flex items-center", children: [
            /* @__PURE__ */ jsx2("span", { children: getLocaleAmount(
              payment.amount,
              payment.currency_code
            ) }),
            /* @__PURE__ */ jsx2("span", { children: "\xA0-\xA0" }),
            /* @__PURE__ */ jsxs2("span", { children: [
              "(#",
              payment.id.substring(23),
              ")"
            ] })
          ] }),
          /* @__PURE__ */ jsx2(
            Form.Field,
            {
              control: form.control,
              name: "amount",
              rules: {
                required: true,
                min: 0,
                max: paymentAmount
              },
              render: ({ field: { onChange, ...field } }) => {
                return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                  /* @__PURE__ */ jsx2(Form.Label, { children: t("fields.amount") }),
                  /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsx2(
                    CurrencyInput2,
                    {
                      ...field,
                      min: 0,
                      placeholder: formatValue2({
                        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
                    }
                  ) }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, {})
                ] });
              }
            }
          ),
          /* @__PURE__ */ jsx2(
            Form.Field,
            {
              control: form.control,
              name: "refund_reason_id",
              render: ({ field }) => {
                return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                  /* @__PURE__ */ jsx2(Form.Label, { children: t("fields.refundReason") }),
                  /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsxs2(
                    Select2,
                    {
                      dir: direction,
                      value: field.value,
                      onValueChange: field.onChange,
                      children: [
                        /* @__PURE__ */ jsx2(Select2.Trigger, { children: /* @__PURE__ */ jsx2(Select2.Value, {}) }),
                        /* @__PURE__ */ jsx2(Select2.Content, { children: refund_reasons?.map((reason) => /* @__PURE__ */ jsx2(Select2.Item, { value: reason.id, children: reason.label }, reason.id)) })
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, {})
                ] });
              }
            }
          ),
          /* @__PURE__ */ jsx2(
            Form.Field,
            {
              control: form.control,
              name: `note`,
              render: ({ field }) => {
                return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                  /* @__PURE__ */ jsx2(Form.Label, { children: t("fields.note") }),
                  /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsx2(Textarea2, { ...field }) }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, {})
                ] });
              }
            }
          )
        ] }) }),
        /* @__PURE__ */ jsx2(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx2(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button2, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx2(
            Button2,
            {
              isLoading: isPending,
              type: "submit",
              variant: "primary",
              size: "small",
              disabled: !!Object.keys(form.formState.errors || {}).length,
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};

// src/routes/orders/order-create-refund/order-create-refund.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var OrderCreateRefund = () => {
  const { t } = useTranslation3();
  const params = useParams();
  const { order } = useOrder(params.id, {
    fields: DEFAULT_FIELDS
  });
  const { plugins = [] } = usePlugins();
  const loyaltyPlugin = getLoyaltyPlugin(plugins);
  return /* @__PURE__ */ jsxs3(RouteDrawer, { children: [
    /* @__PURE__ */ jsx3(RouteDrawer.Header, { children: /* @__PURE__ */ jsx3(Heading, { children: t("orders.payment.createRefund") }) }),
    order && !loyaltyPlugin && /* @__PURE__ */ jsx3(CreateRefundForm, { order }),
    order && loyaltyPlugin && /* @__PURE__ */ jsx3(OrderBalanceSettlementForm, { order })
  ] });
};
export {
  OrderCreateRefund as Component
};
