import {
  getOfferRestockPreview
} from "./chunk-J6XCRFBW.js";
import {
  ReturnShippingPlaceholder
} from "./chunk-YBF45CX5.js";
import {
  useReturnReasons
} from "./chunk-65HHU6D3.js";
import {
  RETURN_POLICY_DAYS
} from "./chunk-VCUUITW6.js";
import {
  useAddReturnItem,
  useAddReturnShipping,
  useCancelReturnRequest,
  useConfirmReturnRequest,
  useDeleteReturnShipping,
  useInitiateReturn,
  useRemoveReturnItem,
  useUpdateReturn,
  useUpdateReturnItem,
  useUpdateReturnShipping
} from "./chunk-OQTL7PXK.js";
import {
  MoneyAmountCell
} from "./chunk-5YZ3G5EZ.js";
import {
  getStylizedAmount
} from "./chunk-XCHKUSUU.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  Combobox
} from "./chunk-VBRTC2VU.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-LRD242C7.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import {
  useShippingOptions
} from "./chunk-VWPNMEOE.js";
import {
  useStockLocations
} from "./chunk-O72AIZUN.js";
import {
  useOrder,
  useOrderPreview
} 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]/returns/create/index.tsx
import { useEffect as useEffect2, useRef, useState as useState3 } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { toast as toast2 } from "@medusajs/ui";
import { useTranslation as useTranslation5 } from "react-i18next";

// src/pages/orders/[id]/returns/create/_components/return-create-form/return-create-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { PencilSquare, Tag } from "@medusajs/icons";
import {
  Button,
  clx,
  CurrencyInput,
  Heading,
  Hint,
  IconButton as IconButton2,
  Switch,
  Text as Text3,
  toast,
  usePrompt
} from "@medusajs/ui";
import { useEffect, useMemo as useMemo3, useState as useState2 } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { useTranslation as useTranslation4 } from "react-i18next";

// src/pages/orders/[id]/returns/create/_components/add-return-items-table/add-return-items-table.tsx
import { useMemo as useMemo2, useState } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/orders/[id]/returns/create/_components/add-return-items-table/use-return-item-table-columns.tsx
import { Checkbox, Text } from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useReturnItemTableColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => /* @__PURE__ */ jsx(
          Checkbox,
          {
            checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
            onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
          }
        ),
        cell: ({ row }) => {
          const isSelectable = row.getCanSelect();
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              disabled: !isSelectable,
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      columnHelper.display({
        id: "product",
        header: t("fields.product"),
        cell: ({ row }) => {
          const title = row.original.product_title ?? row.original.title;
          if (!title) {
            return /* @__PURE__ */ jsx(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full max-w-[300px] items-center gap-x-3 overflow-hidden", children: [
            /* @__PURE__ */ jsx(Thumbnail, { src: row.original.thumbnail }),
            /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "truncate",
                title,
                children: title
              }
            )
          ] });
        }
      }),
      columnHelper.accessor("variant_sku", {
        header: t("fields.sku"),
        cell: ({ getValue }) => {
          const sku = getValue();
          if (!sku) return /* @__PURE__ */ jsx(PlaceholderCell, {});
          return /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "truncate", children: sku });
        }
      }),
      columnHelper.display({
        id: "variant_title",
        header: t("fields.title"),
        cell: ({ row }) => {
          const title = row.original.variant_title;
          if (!title) return /* @__PURE__ */ jsx(PlaceholderCell, {});
          return /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "truncate", children: title });
        }
      }),
      columnHelper.accessor("remainingQuantity", {
        header: t("orders.returns.remainingQuantity", {
          defaultValue: "Remaining"
        }),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "tabular-nums", children: getValue() })
      })
    ],
    [t]
  );
};

// src/pages/orders/[id]/returns/create/_components/add-return-items-table/add-return-items-table.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 50;
var getRemainingQuantity = (item) => {
  const detail = item.detail ?? {};
  const fulfilled = detail.fulfilled_quantity ?? 0;
  const requested = detail.return_requested_quantity ?? 0;
  const returned = detail.returned_quantity ?? 0;
  return fulfilled - requested - returned;
};
var AddReturnItemsTable = ({
  order,
  onSelectionChange,
  selectedItems = []
}) => {
  const { t } = useTranslation2();
  const [rowSelection, setRowSelection] = useState(
    selectedItems.reduce((acc, id) => {
      acc[id] = true;
      return acc;
    }, {})
  );
  const updater = (fn) => {
    const newState = typeof fn === "function" ? fn(rowSelection) : fn;
    setRowSelection(newState);
    onSelectionChange(Object.keys(newState));
  };
  const rows = useMemo2(() => {
    return (order.items ?? []).map((item) => {
      const remainingQuantity = getRemainingQuantity(item);
      if (remainingQuantity <= 0) {
        return null;
      }
      return {
        id: item.id,
        title: item.title,
        product_title: item.product_title,
        variant_sku: item.variant_sku,
        variant_title: item.variant_title,
        thumbnail: item.thumbnail,
        remainingQuantity
      };
    }).filter((r) => r !== null);
  }, [order.items]);
  const count = rows.length;
  const columns = useReturnItemTableColumns();
  const { table } = useDataTable({
    data: rows,
    columns,
    count,
    enablePagination: true,
    // Row id = order line item id; `onSelectionChange` yields the ids the
    // vendor add-return-items route accepts.
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enableRowSelection: () => true,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx2(
    "div",
    {
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "add-return-items-picker",
      children: /* @__PURE__ */ jsx2(
        _DataTable,
        {
          table,
          columns,
          pageSize: PAGE_SIZE,
          count,
          pagination: true,
          layout: "fill",
          search: false,
          orderBy: [
            { key: "product_title", label: t("fields.product") },
            { key: "variant_title", label: t("fields.title") }
          ]
        }
      )
    }
  );
};

// src/pages/orders/[id]/returns/create/_components/return-create-form/return-item.tsx
import { ChatBubble, DocumentText, XCircle, XMark } from "@medusajs/icons";
import { IconButton, Input, Text as Text2 } from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";
import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
function ReturnItem({
  item,
  previewItem,
  currencyCode,
  form,
  onRemove,
  onUpdate,
  index,
  locationId,
  locationName
}) {
  const { t } = useTranslation3();
  const { return_reasons: returnReasons = [] } = useReturnReasons({
    fields: "+label"
  });
  const formItem = form.watch(`items.${index}`);
  const showReturnReason = typeof formItem?.reason_id === "string";
  const showNote = typeof formItem?.note === "string";
  const restockRows = locationId ? getOfferRestockPreview(
    item,
    formItem?.quantity ?? 0
  ) : [];
  const offerSku = item.offer?.sku ?? item.variant_sku ?? null;
  return /* @__PURE__ */ jsxs2(
    "div",
    {
      className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl",
      "data-testid": `return-item-${item.id}`,
      children: [
        /* @__PURE__ */ jsxs2("div", { className: "flex flex-col items-center gap-x-2 gap-y-2 border-b p-3 text-sm md:flex-row", children: [
          /* @__PURE__ */ jsxs2("div", { className: "flex flex-1 items-center gap-x-3", children: [
            /* @__PURE__ */ jsx3(Thumbnail, { src: item.thumbnail }),
            /* @__PURE__ */ jsxs2("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsxs2("div", { children: [
                /* @__PURE__ */ jsxs2(Text2, { className: "txt-small", as: "span", weight: "plus", children: [
                  item.title,
                  " "
                ] }),
                item.variant_sku && /* @__PURE__ */ jsxs2("span", { children: [
                  "(",
                  item.variant_sku,
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ jsx3(Text2, { as: "div", className: "text-ui-fg-subtle txt-small", children: item.product_title })
            ] })
          ] }),
          /* @__PURE__ */ jsxs2("div", { className: "flex flex-1 justify-between", children: [
            /* @__PURE__ */ jsxs2("div", { className: "flex flex-grow items-center gap-2", children: [
              /* @__PURE__ */ jsx3(
                Form.Field,
                {
                  control: form.control,
                  name: `items.${index}.quantity`,
                  render: ({ field }) => {
                    return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                      /* @__PURE__ */ jsx3(Form.Control, { children: /* @__PURE__ */ jsx3(
                        Input,
                        {
                          className: "bg-ui-bg-base txt-small w-[67px] rounded-lg",
                          min: 1,
                          max: item.quantity,
                          type: "number",
                          "data-testid": `return-item-${item.id}-qty`,
                          ...field,
                          onChange: (e) => {
                            const val = e.target.value;
                            const payload = val === "" ? null : Number(val);
                            field.onChange(payload);
                            if (payload) {
                              onUpdate({ quantity: payload });
                            }
                          }
                        }
                      ) }),
                      /* @__PURE__ */ jsx3(Form.ErrorMessage, {})
                    ] });
                  }
                }
              ),
              /* @__PURE__ */ jsx3(Text2, { className: "txt-small text-ui-fg-subtle", children: t("fields.qty") })
            ] }),
            /* @__PURE__ */ jsx3("div", { className: "text-ui-fg-subtle txt-small mr-2 flex flex-shrink-0", children: /* @__PURE__ */ jsx3(
              MoneyAmountCell,
              {
                currencyCode,
                amount: previewItem.return_requested_total
              }
            ) }),
            /* @__PURE__ */ jsx3(
              ActionMenu,
              {
                groups: [
                  {
                    actions: [
                      !showReturnReason && {
                        label: t("actions.addReason"),
                        onClick: () => form.setValue(`items.${index}.reason_id`, ""),
                        icon: /* @__PURE__ */ jsx3(ChatBubble, {})
                      },
                      !showNote && {
                        label: t("actions.addNote"),
                        onClick: () => form.setValue(`items.${index}.note`, ""),
                        icon: /* @__PURE__ */ jsx3(DocumentText, {})
                      },
                      {
                        label: t("actions.remove"),
                        onClick: onRemove,
                        icon: /* @__PURE__ */ jsx3(XCircle, {})
                      }
                    ].filter(Boolean)
                  }
                ]
              }
            )
          ] })
        ] }),
        restockRows.length > 0 && /* @__PURE__ */ jsx3("div", { className: "bg-ui-bg-subtle flex flex-col gap-y-1 rounded-md px-3 py-2", children: restockRows.map((row) => /* @__PURE__ */ jsx3(
          Text2,
          {
            size: "xsmall",
            className: "text-ui-fg-subtle",
            "data-testid": `return-item-${item.id}-restock-${row.inventoryItemId}`,
            children: t("orders.returns.restockPreview", {
              quantity: formItem?.quantity ?? 0,
              offerSku: offerSku ?? "\u2014",
              delta: row.delta,
              inventoryItem: row.inventoryItemLabel,
              location: locationName ?? "\u2014"
            })
          },
          row.inventoryItemId
        )) }),
        /* @__PURE__ */ jsxs2(Fragment, { children: [
          showReturnReason && /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-1 gap-2 p-3 md:grid-cols-2", children: [
            /* @__PURE__ */ jsxs2("div", { children: [
              /* @__PURE__ */ jsx3(Form.Label, { children: t("orders.returns.reason") }),
              /* @__PURE__ */ jsx3(Form.Hint, { className: "!mt-1", children: t("orders.returns.reasonHint") })
            ] }),
            /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsx3("div", { className: "flex-grow", children: /* @__PURE__ */ jsx3(
                Form.Field,
                {
                  control: form.control,
                  name: `items.${index}.reason_id`,
                  render: ({ field: { ref, value, onChange, ...field } }) => {
                    void ref;
                    return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                      /* @__PURE__ */ jsx3(Form.Control, { children: /* @__PURE__ */ jsx3(
                        Combobox,
                        {
                          value: value ?? void 0,
                          onChange: (v) => {
                            onUpdate({ reason_id: v });
                            onChange(v);
                          },
                          ...field,
                          options: returnReasons.map(
                            (reason) => ({
                              label: reason.label ?? reason.value ?? reason.id,
                              value: reason.id
                            })
                          ),
                          "data-testid": `return-item-${item.id}-reason`
                        }
                      ) }),
                      /* @__PURE__ */ jsx3(Form.ErrorMessage, {})
                    ] });
                  }
                }
              ) }),
              /* @__PURE__ */ jsx3(
                IconButton,
                {
                  type: "button",
                  className: "flex-shrink",
                  variant: "transparent",
                  onClick: () => {
                    onUpdate({ reason_id: null });
                    form.setValue(`items.${index}.reason_id`, null);
                  },
                  children: /* @__PURE__ */ jsx3(XMark, { className: "text-ui-fg-muted" })
                }
              )
            ] })
          ] }),
          showNote && /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-1 gap-2 p-3 md:grid-cols-2", children: [
            /* @__PURE__ */ jsxs2("div", { children: [
              /* @__PURE__ */ jsx3(Form.Label, { children: t("orders.returns.note") }),
              /* @__PURE__ */ jsx3(Form.Hint, { className: "!mt-1", children: t("orders.returns.noteHint") })
            ] }),
            /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsx3("div", { className: "flex-grow", children: /* @__PURE__ */ jsx3(
                Form.Field,
                {
                  control: form.control,
                  name: `items.${index}.note`,
                  render: ({ field: { ref, value, onChange, ...field } }) => {
                    void ref;
                    return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                      /* @__PURE__ */ jsx3(Form.Control, { children: /* @__PURE__ */ jsx3(
                        Input,
                        {
                          value: value ?? "",
                          onChange,
                          ...field,
                          onBlur: () => onUpdate({ internal_note: value ?? null }),
                          className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover",
                          "data-testid": `return-item-${item.id}-note`
                        }
                      ) }),
                      /* @__PURE__ */ jsx3(Form.ErrorMessage, {})
                    ] });
                  }
                }
              ) }),
              /* @__PURE__ */ jsx3(
                IconButton,
                {
                  type: "button",
                  className: "flex-shrink",
                  variant: "transparent",
                  onClick: () => {
                    form.setValue(`items.${index}.note`, null);
                    onUpdate({ internal_note: null });
                  },
                  children: /* @__PURE__ */ jsx3(XMark, { className: "text-ui-fg-muted" })
                }
              )
            ] })
          ] })
        ] })
      ]
    }
  );
}

// src/pages/orders/[id]/returns/create/_components/return-create-form/schema.ts
import { z } from "zod";
var ReturnCreateSchema = z.object({
  items: z.array(
    z.object({
      item_id: z.string(),
      quantity: z.number(),
      reason_id: z.string().optional().nullable(),
      note: z.string().optional().nullable()
    })
  ),
  location_id: z.string().optional(),
  option_id: z.string(),
  send_notification: z.boolean().optional(),
  // TODO: receive flow happens on a separate route — left here for parity
  // with the admin schema and possible future inline-receive support.
  receive_now: z.boolean().optional()
});

// src/pages/orders/[id]/returns/create/_components/return-create-form/return-create-form.tsx
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
var selectedLineItemIds = [];
var ReturnCreateForm = ({
  order,
  preview,
  activeReturn
}) => {
  const { t } = useTranslation4();
  const { handleSuccess } = useRouteModal();
  const itemsMap = useMemo3(
    () => new Map((order.items || []).map((i) => [i.id, i])),
    [order.items]
  );
  const previewItems = useMemo3(
    () => preview.items.filter(
      (i) => !!i.actions?.find(
        (a) => a.return_id === activeReturn.id
      )
    ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [preview.items, activeReturn.id]
  );
  const previewItemsMap = useMemo3(
    () => new Map(previewItems.map((i) => [i.id, i])),
    [previewItems]
  );
  const { setIsOpen } = useStackedModal();
  const [isShippingPriceEdit, setIsShippingPriceEdit] = useState2(false);
  const [customShippingAmount, setCustomShippingAmount] = useState2({
    value: "0",
    float: 0
  });
  const { stock_locations: stockLocations = [] } = useStockLocations({
    limit: 999
  });
  const { shipping_options: shippingOptions = [] } = useShippingOptions({
    limit: 999,
    fields: "*prices,+service_zone.fulfillment_set.location.id"
  });
  const { mutateAsync: confirmReturnRequest, isPending: isConfirming } = useConfirmReturnRequest(activeReturn.id, order.id);
  const { mutateAsync: cancelReturnRequest, isPending: isCanceling } = useCancelReturnRequest(activeReturn.id, order.id);
  const { mutateAsync: updateReturnRequest, isPending: isUpdating } = useUpdateReturn(activeReturn.id, order.id);
  const { mutateAsync: addReturnShipping, isPending: isAddingReturnShipping } = useAddReturnShipping(activeReturn.id, order.id);
  const {
    mutateAsync: updateReturnShipping,
    isPending: isUpdatingReturnShipping
  } = useUpdateReturnShipping(activeReturn.id, order.id);
  const {
    mutateAsync: deleteReturnShipping,
    isPending: isDeletingReturnShipping
  } = useDeleteReturnShipping(activeReturn.id, order.id);
  const { mutateAsync: addReturnItem, isPending: isAddingReturnItem } = useAddReturnItem(activeReturn.id, order.id);
  const { mutateAsync: removeReturnItem, isPending: isRemovingReturnItem } = useRemoveReturnItem(activeReturn.id, order.id);
  const { mutateAsync: updateReturnItem, isPending: isUpdatingReturnItem } = useUpdateReturnItem(activeReturn.id, order.id);
  const isRequestLoading = isConfirming || isCanceling || isAddingReturnShipping || isUpdatingReturnShipping || isDeletingReturnShipping || isAddingReturnItem || isRemovingReturnItem || isUpdatingReturnItem || isUpdating;
  const form = useForm({
    defaultValues: () => {
      const method = preview.shipping_methods.find(
        (s) => !!s.actions?.find(
          (a) => a.action === "SHIPPING_ADD"
        )
      );
      return Promise.resolve({
        items: previewItems.map((i) => {
          const actions = i.actions ?? [];
          const returnAction = actions.find((a) => a.action === "RETURN_ITEM");
          return {
            item_id: i.id,
            quantity: i.detail.return_requested_quantity,
            note: returnAction?.internal_note ?? void 0,
            reason_id: returnAction?.details?.reason_id
          };
        }),
        option_id: method ? method.shipping_option_id ?? "" : "",
        location_id: activeReturn?.location_id ?? void 0,
        send_notification: false
      });
    },
    resolver: zodResolver(ReturnCreateSchema)
  });
  const {
    fields: items,
    append,
    remove,
    update
  } = useFieldArray({
    name: "items",
    control: form.control
  });
  useEffect(() => {
    const existingItemsMap = {};
    previewItems.forEach((i) => {
      const ind = items.findIndex((field) => field.item_id === i.id);
      if (!i.detail.return_requested_quantity) {
        return;
      }
      existingItemsMap[i.id] = true;
      if (ind > -1) {
        if (items[ind].quantity !== i.detail.return_requested_quantity) {
          const actions = i.actions ?? [];
          const returnItemAction = actions.find(
            (a) => a.action === "RETURN_ITEM"
          );
          update(ind, {
            ...items[ind],
            quantity: i.detail.return_requested_quantity,
            note: returnItemAction?.internal_note ?? void 0,
            reason_id: returnItemAction?.details?.reason_id
          });
        }
      } else {
        append({
          item_id: i.id,
          quantity: i.detail.return_requested_quantity
        });
      }
    });
    items.forEach((i, ind) => {
      if (!(i.item_id in existingItemsMap)) {
        remove(ind);
      }
    });
  }, [previewItems]);
  useEffect(() => {
    const method = preview.shipping_methods?.find(
      (s) => !!s.actions?.find(
        (a) => a.action === "SHIPPING_ADD"
      )
    );
    if (method) {
      form.setValue("option_id", method.shipping_option_id ?? "");
    } else {
      form.setValue("option_id", "");
    }
  }, [preview.shipping_methods]);
  useEffect(() => {
    form.setValue("location_id", activeReturn?.location_id || "");
  }, [activeReturn]);
  useEffect(() => {
    if (isShippingPriceEdit) {
      document.getElementById("js-shipping-input")?.focus();
    }
  }, [isShippingPriceEdit]);
  const showPlaceholder = !items.length;
  const itemsError = form.formState.errors.items;
  const locationId = form.watch("location_id");
  const shippingOptionId = form.watch("option_id");
  const prompt = usePrompt();
  useEffect(() => {
    if (items.length) {
      form.clearErrors("items");
    }
  }, [items.length]);
  const locationName = useMemo3(() => {
    if (!locationId) return null;
    return stockLocations.find((l) => l.id === locationId)?.name ?? null;
  }, [locationId, stockLocations]);
  const returnTotal = preview.return_requested_total;
  const shippingTotal = useMemo3(() => {
    const method = preview.shipping_methods.find(
      (sm) => !!sm.actions?.find(
        (a) => a.action === "SHIPPING_ADD"
      )
    );
    return method?.total || 0;
  }, [preview.shipping_methods]);
  const estimatedDifference = (preview.summary?.pending_difference || 0) - previewItems.reduce(
    (acc, item) => acc + (item.total ?? 0),
    0
  );
  const handleSubmit = form.handleSubmit(async (data) => {
    if (!items.length) {
      form.setError("items", {
        type: "manual",
        message: t("orders.returns.emptyItemsError")
      });
      return;
    }
    try {
      const res = await prompt({
        title: t("general.areYouSure"),
        description: t("orders.returns.confirmText"),
        confirmText: t("actions.continue"),
        cancelText: t("actions.cancel"),
        variant: "confirmation"
      });
      if (!res) {
        return;
      }
      await confirmReturnRequest({ no_notification: !data.send_notification });
      toast.success(t("orders.returns.toast.confirmedSuccessfully"));
      handleSuccess(`/orders/${order.id}`);
    } catch (e) {
      toast.error(t("general.error"), {
        description: e instanceof Error ? e.message : void 0
      });
    }
  });
  const onItemsSelected = async () => {
    const existingIds = new Set(items.map((i) => i.item_id));
    const newIds = selectedLineItemIds.filter((id) => !existingIds.has(id));
    if (newIds.length === 0) {
      setIsOpen("items", false);
      return;
    }
    try {
      await addReturnItem({
        items: newIds.map((id) => ({
          id,
          quantity: 1
        }))
      });
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      );
    } finally {
      selectedLineItemIds = [];
      setIsOpen("items", false);
    }
  };
  const onLocationChange = async (selectedLocationId) => {
    await updateReturnRequest({ location_id: selectedLocationId });
  };
  const onShippingOptionChange = async (selectedOptionId) => {
    const promises = preview.shipping_methods.map(
      (s) => s.actions?.find(
        (a) => a.action === "SHIPPING_ADD"
      )?.id
    ).filter((id) => !!id).map((id) => deleteReturnShipping(id));
    await Promise.all(promises);
    if (selectedOptionId) {
      await addReturnShipping({ shipping_option_id: selectedOptionId });
    }
  };
  return /* @__PURE__ */ jsx4(
    RouteFocusModal.Form,
    {
      form,
      onClose: (isSubmitSuccessful) => {
        if (!isSubmitSuccessful) {
          cancelReturnRequest();
        }
      },
      children: /* @__PURE__ */ jsxs3(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
        /* @__PURE__ */ jsx4(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx4(RouteFocusModal.Body, { className: "flex size-full justify-center overflow-y-auto", children: /* @__PURE__ */ jsxs3("div", { className: "mt-16 w-[720px] max-w-[100%] px-4 md:p-0", children: [
          /* @__PURE__ */ jsx4(Heading, { level: "h1", children: t("orders.returns.create") }),
          /* @__PURE__ */ jsx4(Text3, { size: "small", className: "text-ui-fg-subtle mt-2", children: t("orders.returns.policyHint", { days: RETURN_POLICY_DAYS }) }),
          /* @__PURE__ */ jsxs3("div", { className: "mt-8 flex items-center justify-between", children: [
            /* @__PURE__ */ jsx4(Heading, { level: "h2", children: t("orders.returns.inbound") }),
            /* @__PURE__ */ jsxs3(StackedFocusModal, { id: "items", children: [
              /* @__PURE__ */ jsx4(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx4(
                Button,
                {
                  type: "button",
                  variant: "secondary",
                  size: "small",
                  "data-testid": "return-create-add-items-trigger",
                  children: t("actions.addItems")
                }
              ) }),
              /* @__PURE__ */ jsxs3(StackedFocusModal.Content, { children: [
                /* @__PURE__ */ jsx4(StackedFocusModal.Header, {}),
                /* @__PURE__ */ jsx4(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("actions.addItems") }) }),
                /* @__PURE__ */ jsx4(StackedFocusModal.Description, { className: "sr-only", children: t("orders.returns.create") }),
                /* @__PURE__ */ jsx4(StackedFocusModal.Body, { className: "size-full overflow-hidden", children: /* @__PURE__ */ jsx4(
                  AddReturnItemsTable,
                  {
                    order,
                    selectedItems: items.map((i) => i.item_id),
                    onSelectionChange: (s) => selectedLineItemIds = s
                  }
                ) }),
                /* @__PURE__ */ jsx4(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsx4("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-end gap-x-2", children: [
                  /* @__PURE__ */ jsx4(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx4(
                    Button,
                    {
                      type: "button",
                      variant: "secondary",
                      size: "small",
                      "data-testid": "return-create-add-items-cancel",
                      children: t("actions.cancel")
                    }
                  ) }),
                  /* @__PURE__ */ jsx4(
                    Button,
                    {
                      type: "button",
                      variant: "primary",
                      size: "small",
                      onClick: onItemsSelected,
                      "data-testid": "return-create-add-items-save",
                      children: t("actions.save")
                    },
                    "submit-button"
                  )
                ] }) }) })
              ] })
            ] })
          ] }),
          showPlaceholder && /* @__PURE__ */ jsxs3("div", { children: [
            /* @__PURE__ */ jsxs3(
              "div",
              {
                className: clx(
                  "bg-ui-bg-field mt-4 flex w-full flex-col items-center justify-center gap-y-3 rounded-lg border px-6 py-8",
                  { "border-ui-border-error": !!itemsError }
                ),
                "data-testid": "return-create-empty-state",
                children: [
                  /* @__PURE__ */ jsx4(Tag, { className: "text-ui-fg-subtle" }),
                  /* @__PURE__ */ jsxs3("div", { className: "flex flex-col items-center gap-y-1", children: [
                    /* @__PURE__ */ jsx4(Text3, { size: "small", leading: "compact", weight: "plus", children: t("orders.returns.emptyState.title") }),
                    /* @__PURE__ */ jsx4(Text3, { size: "small", className: "text-ui-fg-subtle", children: t("orders.returns.emptyState.description") })
                  ] })
                ]
              }
            ),
            itemsError && /* @__PURE__ */ jsx4(
              Hint,
              {
                variant: "error",
                className: "mt-2",
                "data-testid": "return-create-empty-state-error",
                children: itemsError.message
              }
            )
          ] }),
          items.filter((item) => !!previewItemsMap.get(item.item_id)).map((item, index) => {
            const previewItem = previewItemsMap.get(item.item_id);
            if (!previewItem) {
              return null;
            }
            const orderItem = itemsMap.get(item.item_id);
            if (!orderItem) {
              return null;
            }
            return /* @__PURE__ */ jsx4(
              ReturnItem,
              {
                item: orderItem,
                previewItem,
                currencyCode: order.currency_code,
                form,
                locationId,
                locationName,
                onRemove: () => {
                  const actions = previewItems.find((i) => i.id === item.item_id)?.actions ?? [];
                  const actionId = actions.find(
                    (a) => a.action === "RETURN_ITEM"
                  )?.id;
                  if (actionId) {
                    removeReturnItem(actionId);
                  }
                },
                onUpdate: (payload) => {
                  const actions = previewItems.find((i) => i.id === item.item_id)?.actions ?? [];
                  const action = actions.find(
                    (a) => a.action === "RETURN_ITEM"
                  );
                  if (action) {
                    updateReturnItem(
                      { actionId: action.id, ...payload },
                      {
                        onError: (error) => {
                          if (action.details?.quantity && payload.quantity) {
                            form.setValue(
                              `items.${index}.quantity`,
                              action.details.quantity
                            );
                          }
                          toast.error(error.message);
                        }
                      }
                    );
                  }
                },
                index
              },
              item.id
            );
          }),
          !showPlaceholder && /* @__PURE__ */ jsxs3("div", { className: "mt-8 flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsxs3("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
              /* @__PURE__ */ jsxs3("div", { children: [
                /* @__PURE__ */ jsx4(Form.Label, { children: t("orders.returns.location") }),
                /* @__PURE__ */ jsx4(Form.Hint, { className: "!mt-1", children: t("orders.returns.locationHint") })
              ] }),
              /* @__PURE__ */ jsx4(
                Form.Field,
                {
                  control: form.control,
                  name: "location_id",
                  render: ({ field: { value, onChange, ...field } }) => {
                    return /* @__PURE__ */ jsx4(Form.Item, { children: /* @__PURE__ */ jsx4(Form.Control, { children: /* @__PURE__ */ jsx4(
                      Combobox,
                      {
                        value: value ?? void 0,
                        onChange: (v) => {
                          onChange(v);
                          onLocationChange(v ?? "");
                        },
                        ...field,
                        options: (stockLocations ?? []).map(
                          (loc) => ({
                            label: loc.name,
                            value: loc.id
                          })
                        ),
                        "data-testid": "return-create-location"
                      }
                    ) }) });
                  }
                }
              )
            ] }),
            /* @__PURE__ */ jsxs3("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
              /* @__PURE__ */ jsxs3("div", { children: [
                /* @__PURE__ */ jsxs3(Form.Label, { children: [
                  t("orders.returns.inboundShipping"),
                  /* @__PURE__ */ jsxs3(
                    Text3,
                    {
                      size: "small",
                      leading: "compact",
                      className: "text-ui-fg-muted ml-1 inline",
                      children: [
                        "(",
                        t("fields.optional"),
                        ")"
                      ]
                    }
                  )
                ] }),
                /* @__PURE__ */ jsx4(Form.Hint, { className: "!mt-1", children: t("orders.returns.inboundShippingHint") })
              ] }),
              /* @__PURE__ */ jsx4(
                Form.Field,
                {
                  control: form.control,
                  name: "option_id",
                  render: ({ field: { value, onChange, ...field } }) => {
                    return /* @__PURE__ */ jsx4(Form.Item, { children: /* @__PURE__ */ jsx4(Form.Control, { children: /* @__PURE__ */ jsx4(
                      Combobox,
                      {
                        allowClear: true,
                        value,
                        onChange: (v) => {
                          onChange(v ?? "");
                          onShippingOptionChange(v);
                        },
                        ...field,
                        options: (shippingOptions ?? []).filter(
                          (so) => (locationId ? so.service_zone?.fulfillment_set?.location?.id === locationId : true) && !!so.rules?.find(
                            (r) => r.attribute === "is_return" && r.value === "true"
                          )
                        ).map((so) => ({
                          label: so.name,
                          value: so.id
                        })),
                        disabled: !locationId,
                        noResultsPlaceholder: /* @__PURE__ */ jsx4(ReturnShippingPlaceholder, {}),
                        "data-testid": "return-create-shipping-option"
                      }
                    ) }) });
                  }
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs3("div", { className: "mt-8 border-y border-dotted py-4", children: [
            /* @__PURE__ */ jsxs3("div", { className: "mb-2 flex items-center justify-between", children: [
              /* @__PURE__ */ jsx4("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.returns.returnTotal") }),
              /* @__PURE__ */ jsx4("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(
                returnTotal ? -1 * returnTotal : returnTotal ?? 0,
                order.currency_code
              ) })
            ] }),
            /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsx4("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.returns.inboundShipping") }),
              /* @__PURE__ */ jsxs3("span", { className: "txt-small text-ui-fg-subtle flex items-center", children: [
                !isShippingPriceEdit && /* @__PURE__ */ jsx4(
                  IconButton2,
                  {
                    onClick: () => setIsShippingPriceEdit(true),
                    variant: "transparent",
                    className: "text-ui-fg-muted",
                    disabled: showPlaceholder || !shippingOptionId,
                    children: /* @__PURE__ */ jsx4(PencilSquare, {})
                  }
                ),
                isShippingPriceEdit ? /* @__PURE__ */ jsx4(
                  CurrencyInput,
                  {
                    id: "js-shipping-input",
                    onBlur: () => {
                      let actionId;
                      preview.shipping_methods.forEach((s) => {
                        const actions = s.actions;
                        if (actions) {
                          for (const a of actions) {
                            if (a.action === "SHIPPING_ADD") {
                              actionId = a.id;
                            }
                          }
                        }
                      });
                      if (actionId) {
                        updateReturnShipping({
                          actionId,
                          custom_amount: customShippingAmount.float ?? void 0
                        });
                      }
                      setIsShippingPriceEdit(false);
                    },
                    symbol: currencies[order.currency_code.toUpperCase()]?.symbol_native ?? "",
                    code: order.currency_code,
                    onValueChange: (_value, _name, values) => setCustomShippingAmount({
                      value: values?.value ?? "",
                      float: values?.float ?? null
                    }),
                    value: customShippingAmount.value,
                    disabled: showPlaceholder
                  }
                ) : getStylizedAmount(shippingTotal, order.currency_code)
              ] })
            ] }),
            /* @__PURE__ */ jsxs3("div", { className: "mt-4 flex items-center justify-between border-t border-dotted pt-4", children: [
              /* @__PURE__ */ jsx4("span", { className: "txt-small font-medium", children: t("orders.returns.estDifference") }),
              /* @__PURE__ */ jsx4("span", { className: "txt-small font-medium", children: getStylizedAmount(estimatedDifference, order.currency_code) })
            ] })
          ] }),
          /* @__PURE__ */ jsx4("div", { className: "bg-ui-bg-field mt-8 rounded-lg border py-2 pl-2 pr-4", children: /* @__PURE__ */ jsx4(
            Form.Field,
            {
              control: form.control,
              name: "send_notification",
              render: ({ field: { onChange, value, ...field } }) => {
                return /* @__PURE__ */ jsxs3(Form.Item, { children: [
                  /* @__PURE__ */ jsxs3("div", { className: "flex items-center", children: [
                    /* @__PURE__ */ jsx4(Form.Control, { className: "mr-4 self-start", children: /* @__PURE__ */ jsx4(
                      Switch,
                      {
                        dir: "ltr",
                        className: "mt-[2px] rtl:rotate-180",
                        checked: !!value,
                        onCheckedChange: onChange,
                        ...field,
                        "data-testid": "return-create-notify"
                      }
                    ) }),
                    /* @__PURE__ */ jsxs3("div", { className: "block", children: [
                      /* @__PURE__ */ jsx4(Form.Label, { children: t("orders.returns.sendNotification") }),
                      /* @__PURE__ */ jsx4(Form.Hint, { className: "!mt-1", children: t("orders.returns.sendNotificationHint") })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx4(Form.ErrorMessage, {})
                ] });
              }
            }
          ) }),
          /* @__PURE__ */ jsx4("div", { className: "p-8" })
        ] }) }),
        /* @__PURE__ */ jsx4(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsx4("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx4(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx4(
            Button,
            {
              type: "button",
              variant: "secondary",
              size: "small",
              "data-testid": "return-create-cancel",
              children: t("orders.returns.cancel.title")
            }
          ) }),
          /* @__PURE__ */ jsx4(
            Button,
            {
              type: "submit",
              variant: "primary",
              size: "small",
              isLoading: isRequestLoading,
              "data-testid": "return-create-confirm",
              children: t("orders.returns.confirm")
            },
            "submit-button"
          )
        ] }) }) })
      ] })
    }
  );
};

// src/pages/orders/[id]/returns/create/index.tsx
import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
var Component = () => {
  const { t } = useTranslation5();
  return /* @__PURE__ */ jsxs4(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx5(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx5("span", { className: "sr-only", children: t("orders.returns.create") }) }),
    /* @__PURE__ */ jsx5(RouteFocusModal.Description, { className: "sr-only", children: t("orders.returns.confirmText") }),
    /* @__PURE__ */ jsx5(ReturnCreateContent, {})
  ] });
};
var create_default = Component;
var ReturnCreateContent = () => {
  const { id } = useParams();
  const { t } = useTranslation5();
  const navigate = useNavigate();
  const orderId = id ?? "";
  const { order } = useOrder(orderId, {
    // Use `<rel>.*` and bare scalar names. Combining `*foo` with
    // `*foo.bar` (or `+foo.bar.baz`) makes the Medusa query parser look
    // up a literal `*items` / `+items` on Order and 500s. See
    // packages/core/src/api/vendor/orders/query-config.ts.
    fields: "currency_code,total,items.*,items.variant.*,items.offer.*,items.offer.inventory_item_link.*,items.offer.inventory_item_link.required_quantity,items.offer.inventory_item_link.inventory_item.*,items.offer.inventory_item_link.inventory_item.location_levels.*"
  });
  const { order: preview } = useOrderPreview(orderId);
  const [activeReturn, setActiveReturn] = useState3(
    void 0
  );
  const isInitiatingRef = useRef(false);
  const { mutateAsync: initiateReturn } = useInitiateReturn(orderId);
  useEffect2(() => {
    async function run() {
      if (isInitiatingRef.current || activeReturn || !order || !preview) {
        return;
      }
      isInitiatingRef.current = true;
      try {
        const res = await initiateReturn({ order_id: orderId });
        const r = res?.return;
        if (r) {
          setActiveReturn(r);
        }
      } catch (e) {
        toast2.error(
          e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
        );
        navigate(`/orders/${orderId}`, { replace: true });
      } finally {
        isInitiatingRef.current = false;
      }
    }
    run();
  }, [order, preview, activeReturn, initiateReturn, orderId, navigate, t]);
  const ready = !!(order && preview && activeReturn);
  if (!ready) {
    return null;
  }
  return /* @__PURE__ */ jsx5(
    ReturnCreateForm,
    {
      order,
      preview,
      activeReturn
    }
  );
};
export {
  Component,
  create_default as default
};
