import {
  display_id_default
} from "./chunk-WQTWBXKO.js";
import {
  getDecimalDigits,
  getLocaleAmount
} from "./chunk-XCHKUSUU.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  useRefundPayment,
  useRefundReasons
} from "./chunk-VUWAOX7H.js";
import {
  useOrder
} from "./chunk-DIAWPVYS.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

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

// src/pages/orders/[id]/refund/_components/create-refund-form/create-refund-form.tsx
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { formatValue } from "react-currency-input-field";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  CurrencyInput,
  Heading,
  Select,
  Textarea,
  toast
} from "@medusajs/ui";
import { jsx, jsxs } from "react/jsx-runtime";
var CreateRefundForm = ({ order }) => {
  const { t } = useTranslation();
  const dir = useDocumentDirection();
  const { handleSuccess } = useRouteModal();
  const [searchParams] = useSearchParams();
  const requestedPaymentId = searchParams.get("payment_id") ?? "";
  const { refund_reasons } = useRefundReasons({ limit: 100 });
  const payment = useMemo(() => {
    const allPayments = (order.payment_collections ?? []).flatMap(
      (pc) => pc.payments ?? []
    );
    if (requestedPaymentId) {
      return allPayments.find((p) => p.id === requestedPaymentId);
    }
    return allPayments.find((p) => {
      const refunded = (p.refunds ?? []).reduce(
        (acc, r) => acc + (r.amount ?? 0),
        0
      );
      return !!p.captured_at && !p.canceled_at && refunded < p.amount;
    });
  }, [order, requestedPaymentId]);
  const paymentId = payment?.id ?? "";
  const refundedAmount = useMemo(() => {
    if (!payment) return 0;
    return (payment.refunds ?? []).reduce(
      (acc, r) => acc + (r.amount ?? 0),
      0
    );
  }, [payment]);
  const remaining = useMemo(() => {
    if (!payment) return 0;
    return Math.max(0, payment.amount - refundedAmount);
  }, [payment, refundedAmount]);
  const currency = useMemo(
    () => currencies[order.currency_code.toUpperCase()],
    [order.currency_code]
  );
  const decimalDigits = getDecimalDigits(order.currency_code);
  const getRoundedAmount = (amount) => amount.toLocaleString("en-US", {
    minimumFractionDigits: decimalDigits,
    maximumFractionDigits: decimalDigits,
    useGrouping: false
  });
  const RefundSchema = useMemo(
    () => z.object({
      amount: z.object({
        value: z.union([z.string(), z.number()]),
        float: z.number().nullable()
      }).refine((v) => v.float !== null && v.float > 0, {
        message: t("orders.payment.enterAmount")
      }),
      refund_reason_id: z.string().optional(),
      note: z.string().optional()
    }),
    [t]
  );
  const refundPayment = useRefundPayment(order.id, paymentId);
  const form = useForm({
    resolver: zodResolver(RefundSchema),
    defaultValues: {
      amount: {
        value: getRoundedAmount(remaining),
        float: remaining
      },
      refund_reason_id: void 0,
      note: ""
    }
  });
  const handleSubmit = form.handleSubmit(async (values) => {
    const amount = values.amount.float ?? 0;
    if (amount > remaining) {
      form.setError("amount", {
        message: t("orders.payment.createRefundWrongQuantity", {
          number: remaining
        })
      });
      return;
    }
    await refundPayment.mutateAsync(
      {
        amount,
        refund_reason_id: values.refund_reason_id,
        note: values.note?.trim() ? values.note.trim() : void 0
      },
      {
        onSuccess: () => {
          toast.success(
            t("orders.payment.refundPaymentSuccess", {
              amount: getLocaleAmount(amount, order.currency_code)
            })
          );
          handleSuccess(`/orders/${order.id}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  if (!payment) {
    return null;
  }
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex flex-1 flex-col", children: [
    /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-base flex items-center gap-x-1 text-sm", children: [
        /* @__PURE__ */ jsx("span", { children: getLocaleAmount(
          payment.amount,
          order.currency_code
        ) }),
        /* @__PURE__ */ jsx("span", { children: "-" }),
        /* @__PURE__ */ jsxs("span", { children: [
          "(",
          /* @__PURE__ */ jsx(display_id_default, { id: payment.id }),
          ")"
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "amount",
          render: ({ field: { onChange, ...field } }) => /* @__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
                }),
                "data-testid": "refund-amount-input"
              }
            ) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, {})
          ] })
        }
      ),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "refund_reason_id",
          render: ({ field: { ref, onChange, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
            /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("orders.returns.reason") }),
            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { onValueChange: onChange, ...field, dir, children: [
              /* @__PURE__ */ jsx(
                Select.Trigger,
                {
                  ref,
                  "data-testid": "refund-reason-select",
                  children: /* @__PURE__ */ jsx(Select.Value, {})
                }
              ),
              /* @__PURE__ */ jsx(Select.Content, { children: (refund_reasons ?? []).map((r) => /* @__PURE__ */ jsx(Select.Item, { value: r.id, children: r.label }, r.id)) })
            ] }) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, {})
          ] })
        }
      ),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "note",
          render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
            /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.note") }),
            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
              Textarea,
              {
                "data-testid": "refund-note-input",
                ...field,
                value: field.value ?? ""
              }
            ) }),
            /* @__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, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          size: "small",
          type: "submit",
          isLoading: refundPayment.isPending,
          "data-testid": "refund-submit-button",
          children: t("actions.save")
        }
      )
    ] }) })
  ] }) });
};

// src/pages/orders/[id]/refund/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var Component = () => {
  const { id } = useParams();
  const { t } = useTranslation2();
  const orderId = id ?? "";
  const { order, isLoading, isError, error } = useOrder(orderId, {
    fields: "+currency_code,*payment_collections.payments.refunds"
  });
  if (isError) {
    throw error;
  }
  const ready = !isLoading && !!order;
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsxs2(RouteDrawer.Header, { children: [
      /* @__PURE__ */ jsx2(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx2(Heading2, { children: t("orders.payment.createRefund") }) }),
      /* @__PURE__ */ jsx2(RouteDrawer.Description, { className: "sr-only", children: t("orders.payment.createRefund") })
    ] }),
    ready && /* @__PURE__ */ jsx2(CreateRefundForm, { order })
  ] });
};
var refund_default = Component;
export {
  Component,
  refund_default as default
};
