import {
  ItemPlaceholder
} from "./chunk-ZHFFTT3I.js";
import {
  getOfferRestockPreview
} from "./chunk-J6XCRFBW.js";
import {
  useReturnReasons
} from "./chunk-65HHU6D3.js";
import {
  useAddExchangeInboundItems,
  useAddExchangeInboundShipping,
  useAddExchangeOutboundItems,
  useAddExchangeOutboundShipping,
  useCancelExchangeBegin,
  useCreateExchange,
  useRemoveExchangeInboundItem,
  useRemoveExchangeOutboundItem,
  useRequestExchange,
  useUpdateExchangeInboundItem,
  useUpdateExchangeOutboundItem
} from "./chunk-2GVPLCQR.js";
import {
  getReturnableQuantity
} from "./chunk-UM7ZR3VU.js";
import {
  EXCHANGE_POLICY_DAYS
} from "./chunk-VCUUITW6.js";
import {
  MoneyAmountCell
} from "./chunk-5YZ3G5EZ.js";
import {
  getStylizedAmount
} from "./chunk-XCHKUSUU.js";
import {
  ProductCell,
  ProductHeader
} from "./chunk-FWPGOIFA.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import "./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 {
  useQueryParams
} from "./chunk-THHRRYRS.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 {
  useOffers
} from "./chunk-5DKUSZQ7.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]/exchanges/create/index.tsx
import { useTranslation as useTranslation12 } from "react-i18next";

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-create-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button as Button3, Heading as Heading3, Switch, Text as Text5, toast as toast3, usePrompt } from "@medusajs/ui";
import { useEffect as useEffect3, useMemo as useMemo7, useState as useState3 } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation as useTranslation11 } from "react-i18next";

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-inbound-section.tsx
import { Button, Heading, Text as Text2, toast } from "@medusajs/ui";
import { useEffect, useMemo as useMemo3 } from "react";
import { useFieldArray } from "react-hook-form";
import { useTranslation as useTranslation5 } from "react-i18next";

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

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-inbound-items-table/use-exchange-item-table-columns.tsx
import { Checkbox } from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { jsx } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useExchangeItemTableColumns = (currencyCode) => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__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: () => /* @__PURE__ */ jsx(ProductHeader, {}),
        cell: ({ row }) => /* @__PURE__ */ jsx(
          ProductCell,
          {
            product: {
              thumbnail: row.original.thumbnail,
              title: row.original.product_title
            }
          }
        )
      }),
      columnHelper.accessor("variant.sku", {
        header: t("fields.sku"),
        cell: ({ getValue }) => {
          return getValue() || "-";
        }
      }),
      columnHelper.accessor("variant.title", {
        header: t("fields.variant")
      }),
      columnHelper.accessor("quantity", {
        header: () => /* @__PURE__ */ jsx("div", { className: "flex size-full items-center overflow-hidden text-right", children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t("fields.quantity") }) }),
        cell: ({ row }) => {
          return getReturnableQuantity(row.original);
        }
      }),
      columnHelper.accessor("refundable_total", {
        header: () => /* @__PURE__ */ jsx("div", { className: "flex size-full items-center justify-end overflow-hidden text-right", children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t("fields.price") }) }),
        cell: ({ getValue }) => {
          const amount = getValue() || 0;
          const stylized = getStylizedAmount(amount, currencyCode);
          return /* @__PURE__ */ jsx("div", { className: "flex size-full items-center justify-end overflow-hidden text-right", children: /* @__PURE__ */ jsx("span", { className: "truncate", children: stylized }) });
        }
      })
    ],
    [t, currencyCode]
  );
};

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-inbound-items-table/use-exchange-item-table-filters.tsx
import { useTranslation as useTranslation2 } from "react-i18next";
var useExchangeItemTableFilters = () => {
  const { t } = useTranslation2();
  const filters = [
    {
      key: "created_at",
      label: t("fields.createdAt"),
      type: "date"
    },
    {
      key: "updated_at",
      label: t("fields.updatedAt"),
      type: "date"
    }
  ];
  return filters;
};

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-inbound-items-table/use-exchange-item-table-query.tsx
var useExchangeItemTableQuery = ({
  pageSize = 50,
  prefix
}) => {
  const raw = useQueryParams(
    ["q", "offset", "order", "created_at", "updated_at"],
    prefix
  );
  const { offset, created_at, updated_at, ...rest } = raw;
  const searchParams = {
    ...rest,
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    created_at: created_at ? JSON.parse(created_at) : void 0,
    updated_at: updated_at ? JSON.parse(updated_at) : void 0
  };
  return { searchParams, raw };
};

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-inbound-items-table/add-exchange-inbound-items-table.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 50;
var PREFIX = "rit";
var AddExchangeInboundItemsTable = ({
  onSelectionChange,
  selectedItems,
  items,
  currencyCode
}) => {
  const { t } = useTranslation3();
  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 { searchParams, raw } = useExchangeItemTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const queriedItems = useMemo2(() => {
    const { order, offset, limit, q, created_at, updated_at } = searchParams;
    let results = items;
    if (q) {
      const needle = q.toLowerCase();
      results = results.filter((i) => {
        return i.product_title?.toLowerCase().includes(needle) || i.variant_title?.toLowerCase().includes(needle) || i.variant_sku?.toLowerCase().includes(needle);
      });
    }
    if (order) {
      const direction = order[0] === "-" ? "desc" : "asc";
      const field = order.replace("-", "");
      results = sortItems(results, field, direction);
    }
    if (created_at) {
      results = filterByDate(
        results,
        created_at,
        "created_at"
      );
    }
    if (updated_at) {
      results = filterByDate(
        results,
        updated_at,
        "updated_at"
      );
    }
    return results.slice(offset, offset + limit);
  }, [items, searchParams]);
  const columns = useExchangeItemTableColumns(currencyCode);
  const filters = useExchangeItemTableFilters();
  const { table } = useDataTable({
    data: queriedItems,
    columns,
    count: queriedItems.length,
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enableRowSelection: (row) => {
      return getReturnableQuantity(row.original) > 0;
    },
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col overflow-hidden", children: /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count: queriedItems.length,
      filters,
      pagination: true,
      layout: "fill",
      search: true,
      orderBy: [
        { key: "product_title", label: t("fields.product") },
        { key: "variant_title", label: t("fields.variant") },
        { key: "sku", label: t("fields.sku") }
      ],
      prefix: PREFIX,
      queryObject: raw
    }
  ) });
};
var sortItems = (items, field, direction) => {
  return items.sort((a, b) => {
    let aValue;
    let bValue;
    if (field === "product_title") {
      aValue = a.product_title;
      bValue = b.product_title;
    } else if (field === "variant_title") {
      aValue = a.variant_title;
      bValue = b.variant_title;
    } else if (field === "sku") {
      aValue = a.variant_sku;
      bValue = b.variant_sku;
    }
    const aSafe = aValue ?? "";
    const bSafe = bValue ?? "";
    if (aSafe < bSafe) {
      return direction === "asc" ? -1 : 1;
    }
    if (aSafe > bSafe) {
      return direction === "asc" ? 1 : -1;
    }
    return 0;
  });
};
var filterByDate = (items, date, field) => {
  const { gt, gte, lt, lte } = date;
  return items.filter((i) => {
    const itemDate = new Date(i[field]);
    let isValid = true;
    if (gt) {
      isValid = isValid && itemDate > new Date(gt);
    }
    if (gte) {
      isValid = isValid && itemDate >= new Date(gte);
    }
    if (lt) {
      isValid = isValid && itemDate < new Date(lt);
    }
    if (lte) {
      isValid = isValid && itemDate <= new Date(lte);
    }
    return isValid;
  });
};

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

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-inbound-section.tsx
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
var itemsToAdd = [];
var itemsToRemove = [];
var ExchangeInboundSection = ({
  order,
  preview,
  exchange,
  form,
  orderReturn
}) => {
  const { t } = useTranslation5();
  const { setIsOpen } = useStackedModal();
  const { mutateAsync: addInboundShipping } = useAddExchangeInboundShipping(
    exchange.id,
    order.id
  );
  const { mutateAsync: addInboundItem } = useAddExchangeInboundItems(
    exchange.id,
    order.id
  );
  const { mutateAsync: updateInboundItem } = useUpdateExchangeInboundItem(
    exchange.id,
    order.id
  );
  const { mutateAsync: removeInboundItem } = useRemoveExchangeInboundItem(
    exchange.id,
    order.id
  );
  const previewInboundItems = useMemo3(
    () => (preview?.items ?? []).filter(
      (i) => !!i.actions?.find((a) => a.exchange_id === exchange.id)
    ),
    [preview.items, exchange.id]
  );
  const inboundPreviewItems = previewInboundItems.filter(
    (item) => !!item.actions?.find((a) => a.action === "RETURN_ITEM")
  );
  const itemsMap = useMemo3(
    () => new Map((order?.items ?? []).map((i) => [i.id, i])),
    [order.items]
  );
  const locationId = form.watch("location_id");
  const { stock_locations = [] } = useStockLocations({
    limit: 999
  });
  const { shipping_options = [] } = useShippingOptions(
    {
      limit: 999,
      stock_location_id: locationId
    },
    { enabled: !!locationId }
  );
  const inboundShippingOptions = shipping_options.filter(
    (shippingOption) => !!shippingOption.rules?.find(
      (r) => r.attribute === "is_return" && r.value === "true"
    )
  );
  const {
    fields: inboundItems,
    append,
    remove,
    update
  } = useFieldArray({
    name: "inbound_items",
    control: form.control
  });
  const inboundItemsMap = useMemo3(
    () => new Map(previewInboundItems.map((i) => [i.id, i])),
    [previewInboundItems]
  );
  useEffect(() => {
    const existingItemsMap = {};
    inboundPreviewItems.forEach((i) => {
      const ind = inboundItems.findIndex((field) => field.item_id === i.id);
      const requested = i.detail?.return_requested_quantity ?? 0;
      existingItemsMap[i.id] = true;
      if (ind > -1) {
        if (inboundItems[ind].quantity !== requested) {
          const returnItemAction = i.actions?.find(
            (a) => a.action === "RETURN_ITEM"
          );
          update(ind, {
            ...inboundItems[ind],
            quantity: requested,
            note: returnItemAction?.internal_note ?? void 0,
            reason_id: returnItemAction?.details?.reason_id
          });
        }
      } else {
        append(
          { item_id: i.id, quantity: requested },
          { shouldFocus: false }
        );
      }
    });
    inboundItems.forEach((i, ind) => {
      if (!(i.item_id in existingItemsMap)) {
        remove(ind);
      }
    });
  }, [previewInboundItems]);
  useEffect(() => {
    const inboundShippingMethod = (preview.shipping_methods ?? []).find(
      (s) => s.actions?.find((a) => a.action === "SHIPPING_ADD" && !!a.return_id)
    );
    if (inboundShippingMethod?.shipping_option_id) {
      form.setValue("inbound_option_id", inboundShippingMethod.shipping_option_id);
    } else {
      form.setValue("inbound_option_id", "");
    }
  }, [preview.shipping_methods]);
  useEffect(() => {
    if (orderReturn?.location_id) {
      form.setValue("location_id", orderReturn.location_id);
    }
  }, [orderReturn]);
  const showInboundItemsPlaceholder = !inboundItems.length;
  const onItemsSelected = async () => {
    if (itemsToAdd.length) {
      await addInboundItem(
        {
          items: itemsToAdd.map((id) => ({
            id,
            quantity: 1
          }))
        },
        {
          onError: (error) => {
            toast.error(error.message);
          }
        }
      );
    }
    for (const itemToRemove of itemsToRemove) {
      const actionId = previewInboundItems.find((i) => i.id === itemToRemove)?.actions?.find((a) => a.action === "RETURN_ITEM")?.id;
      if (actionId) {
        await removeInboundItem(actionId, {
          onError: (error) => {
            toast.error(error.message);
          }
        });
      }
    }
    setIsOpen("inbound-items", false);
  };
  const onLocationChange = (_selectedLocationId) => {
  };
  const onShippingOptionChange = async (selectedOptionId) => {
    if (selectedOptionId) {
      await addInboundShipping(
        { shipping_option_id: selectedOptionId },
        {
          onError: (error) => {
            toast.error(error.message);
          }
        }
      );
    }
  };
  return /* @__PURE__ */ jsxs2("div", { children: [
    /* @__PURE__ */ jsxs2("div", { className: "mt-8 flex items-center justify-between", children: [
      /* @__PURE__ */ jsx4(Heading, { level: "h2", children: t("orders.returns.inbound") }),
      /* @__PURE__ */ jsxs2(StackedFocusModal, { id: "inbound-items", children: [
        /* @__PURE__ */ jsx4(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx4(
          "a",
          {
            href: "#",
            onClick: (e) => e.preventDefault(),
            className: "focus-visible:shadow-borders-focus transition-fg txt-compact-small-plus cursor-pointer text-blue-500 outline-none hover:text-blue-400",
            children: t("actions.addItems")
          }
        ) }),
        /* @__PURE__ */ jsxs2(StackedFocusModal.Content, { children: [
          /* @__PURE__ */ jsx4(StackedFocusModal.Header, {}),
          /* @__PURE__ */ jsx4(
            AddExchangeInboundItemsTable,
            {
              items: order.items ?? [],
              selectedItems: inboundItems.map((i) => i.item_id),
              currencyCode: order.currency_code,
              onSelectionChange: (finalSelection) => {
                const alreadySelected = inboundItems.map((i) => i.item_id);
                itemsToAdd = finalSelection.filter(
                  (selection) => !alreadySelected.includes(selection)
                );
                itemsToRemove = alreadySelected.filter(
                  (selection) => !finalSelection.includes(selection)
                );
              }
            }
          ),
          /* @__PURE__ */ jsx4(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsx4("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs2("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", children: t("actions.cancel") }) }),
            /* @__PURE__ */ jsx4(
              Button,
              {
                type: "submit",
                variant: "primary",
                size: "small",
                onClick: async () => await onItemsSelected(),
                children: t("actions.save")
              },
              "submit-button"
            )
          ] }) }) })
        ] })
      ] })
    ] }),
    showInboundItemsPlaceholder && /* @__PURE__ */ jsx4(ItemPlaceholder, {}),
    inboundItems.map((item, index) => {
      const previewItem = inboundItemsMap.get(item.item_id);
      const sourceItem = itemsMap.get(item.item_id);
      if (!previewItem || !sourceItem) {
        return null;
      }
      const locationName = stock_locations.find(
        (l) => l.id === locationId
      )?.name ?? null;
      return /* @__PURE__ */ jsx4(
        ExchangeInboundItem,
        {
          item: sourceItem,
          previewItem,
          currencyCode: order.currency_code,
          form,
          locationName,
          onRemove: () => {
            const actionId = previewInboundItems.find((i) => i.id === item.item_id)?.actions?.find((a) => a.action === "RETURN_ITEM")?.id;
            if (actionId) {
              removeInboundItem(actionId, {
                onError: (error) => {
                  toast.error(error.message);
                }
              });
            }
          },
          onUpdate: (payload) => {
            const action = previewInboundItems.find((i) => i.id === item.item_id)?.actions?.find((a) => a.action === "RETURN_ITEM");
            if (action?.id) {
              updateInboundItem(
                { $actionId: action.id, ...payload },
                {
                  onError: (error) => {
                    if (action.details?.quantity && payload.quantity) {
                      form.setValue(
                        `inbound_items.${index}.quantity`,
                        action.details.quantity
                      );
                    }
                    toast.error(error.message);
                  }
                }
              );
            }
          },
          index
        },
        item.id
      );
    }),
    !showInboundItemsPlaceholder && /* @__PURE__ */ jsxs2("div", { className: "mt-8 flex flex-col gap-y-4", children: [
      /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs2("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,
                {
                  ...field,
                  value: value ?? void 0,
                  onChange: (v) => {
                    onChange(v);
                    onLocationChange(v);
                  },
                  options: stock_locations.map((stockLocation) => ({
                    label: stockLocation.name,
                    value: stockLocation.id
                  }))
                }
              ) }) });
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs2("div", { children: [
          /* @__PURE__ */ jsxs2(Form.Label, { children: [
            t("orders.returns.inboundShipping"),
            /* @__PURE__ */ jsxs2(
              Text2,
              {
                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: "inbound_option_id",
            render: ({ field: { value, onChange, ...field } }) => {
              return /* @__PURE__ */ jsx4(Form.Item, { children: /* @__PURE__ */ jsx4(Form.Control, { children: /* @__PURE__ */ jsx4(
                Combobox,
                {
                  allowClear: true,
                  value: value ?? void 0,
                  onChange: (val) => {
                    onChange(val);
                    onShippingOptionChange(val);
                  },
                  ...field,
                  options: inboundShippingOptions.map((so) => ({
                    label: so.name,
                    value: so.id
                  })),
                  disabled: !locationId
                }
              ) }) });
            }
          }
        )
      ] })
    ] })
  ] });
};

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-outbound-section.tsx
import { Button as Button2, Heading as Heading2, toast as toast2 } from "@medusajs/ui";
import { useEffect as useEffect2, useMemo as useMemo6 } from "react";
import { useFieldArray as useFieldArray2 } from "react-hook-form";
import { useTranslation as useTranslation10 } from "react-i18next";

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-outbound-items-table/add-exchange-outbound-items-table.tsx
import { useMemo as useMemo5, useState as useState2 } from "react";
import { useTranslation as useTranslation8 } from "react-i18next";

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

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-outbound-items-table/use-exchange-outbound-item-table-filters.tsx
import { useTranslation as useTranslation7 } from "react-i18next";
var useExchangeOutboundItemTableFilters = () => {
  const { t } = useTranslation7();
  const filters = [
    {
      key: "created_at",
      label: t("fields.createdAt"),
      type: "date"
    },
    {
      key: "updated_at",
      label: t("fields.updatedAt"),
      type: "date"
    }
  ];
  return filters;
};

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-outbound-items-table/use-exchange-outbound-item-table-query.tsx
var useExchangeOutboundItemTableQuery = ({
  pageSize = 50,
  prefix
}) => {
  const raw = useQueryParams(
    ["q", "offset", "order", "created_at", "updated_at"],
    prefix
  );
  const { offset, created_at, updated_at, ...rest } = raw;
  const searchParams = {
    ...rest,
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    created_at: created_at ? JSON.parse(created_at) : void 0,
    updated_at: updated_at ? JSON.parse(updated_at) : void 0
  };
  return { searchParams, raw };
};

// src/pages/orders/[id]/exchanges/create/_components/add-exchange-outbound-items-table/add-exchange-outbound-items-table.tsx
import { jsx as jsx6 } from "react/jsx-runtime";
var PAGE_SIZE2 = 50;
var PREFIX2 = "rit";
var OFFER_PICKER_FIELDS = [
  "id",
  "sku",
  "variant_id",
  "seller_id",
  "prices.amount",
  "prices.currency_code",
  "product_variant.id",
  "product_variant.title",
  "product_variant.product.id",
  "product_variant.product.title",
  "product_variant.product.thumbnail",
  "product_variant.manage_inventory",
  "product_variant.inventory_quantity",
  "product_variant.inventory_items.required_quantity",
  "product_variant.inventory_items.inventory.location_levels.available_quantity"
].join(",");
var offerHasInventory = (offer) => {
  const variant = offer.product_variant;
  if (!variant) return false;
  if (variant.manage_inventory === false) return true;
  const links = variant.inventory_items ?? [];
  if (!links.length) {
    return (variant.inventory_quantity ?? 0) > 0;
  }
  return links.every((link) => {
    const available = (link.inventory?.location_levels ?? []).reduce(
      (acc, lvl) => acc + (lvl.available_quantity ?? 0),
      0
    );
    const required = link.required_quantity ?? 1;
    return required > 0 && available >= required;
  });
};
var AddExchangeOutboundItemsTable = ({
  currencyCode,
  onSelectionChange,
  selectedItems = []
}) => {
  const { t } = useTranslation8();
  const [rowSelection, setRowSelection] = useState2(
    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 { searchParams, raw } = useExchangeOutboundItemTableQuery({
    pageSize: PAGE_SIZE2,
    prefix: PREFIX2
  });
  const offersResponse = useOffers({
    ...searchParams,
    fields: OFFER_PICKER_FIELDS
  });
  const rawOffers = useMemo5(
    () => offersResponse.offers ?? [],
    [offersResponse.offers]
  );
  const rawCount = offersResponse.count ?? 0;
  const offers = useMemo5(() => {
    return rawOffers.filter((offer) => {
      if (currencyCode) {
        const hasPrice = (offer.prices ?? []).some(
          (p) => p.currency_code === currencyCode
        );
        if (!hasPrice) return false;
      }
      return offerHasInventory(offer);
    });
  }, [rawOffers, currencyCode]);
  const count = offers.length;
  void rawCount;
  const columns = useExchangeOutboundItemTableColumns();
  const filters = useExchangeOutboundItemTableFilters();
  const { table } = useDataTable({
    data: offers,
    columns,
    count,
    enablePagination: true,
    // Row id = offer id so onSelectionChange yields offer_ids that the
    // modal layer sends to the backend item-add routes (which accept
    // `offer_id` and resolve to variant_id + unit_price server-side).
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE2,
    enableRowSelection: () => true,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx6(
    "div",
    {
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "add-offers-picker",
      children: /* @__PURE__ */ jsx6(
        _DataTable,
        {
          table,
          columns,
          pageSize: PAGE_SIZE2,
          count,
          filters,
          pagination: true,
          layout: "fill",
          search: true,
          orderBy: [
            { key: "sku", label: t("fields.sku") },
            { key: "created_at", label: t("fields.createdAt") },
            { key: "updated_at", label: t("fields.updatedAt") }
          ],
          prefix: PREFIX2,
          queryObject: raw
        }
      )
    }
  );
};

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-outbound-item.tsx
import { XCircle as XCircle2 } from "@medusajs/icons";
import { Input as Input2, Text as Text4 } from "@medusajs/ui";
import { useTranslation as useTranslation9 } from "react-i18next";
import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
function ExchangeOutboundItem({
  previewItem,
  currencyCode,
  form,
  onRemove,
  onUpdate,
  index
}) {
  const { t } = useTranslation9();
  const appliedPromoCodes = (previewItem.adjustments ?? []).map((adjustment) => adjustment.code).filter((code) => Boolean(code));
  return /* @__PURE__ */ jsx7(
    "div",
    {
      className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl",
      "data-testid": `exchange-outbound-item-${previewItem.id}`,
      children: /* @__PURE__ */ jsxs4("div", { className: "flex flex-col items-center gap-x-3 gap-y-2 p-3 text-sm md:flex-row", children: [
        /* @__PURE__ */ jsxs4("div", { className: "flex flex-1 items-center gap-x-3", children: [
          /* @__PURE__ */ jsx7(Thumbnail, { src: previewItem.thumbnail ?? void 0 }),
          /* @__PURE__ */ jsxs4("div", { className: "flex flex-grow flex-col", children: [
            /* @__PURE__ */ jsxs4("div", { children: [
              /* @__PURE__ */ jsxs4(Text4, { className: "txt-small", as: "span", weight: "plus", children: [
                previewItem.title,
                " "
              ] }),
              previewItem.variant_sku && /* @__PURE__ */ jsxs4("span", { children: [
                "(",
                previewItem.variant_sku,
                ")"
              ] })
            ] }),
            /* @__PURE__ */ jsx7(Text4, { as: "div", className: "text-ui-fg-subtle txt-small", children: previewItem.subtitle ?? previewItem.variant_title ?? "" })
          ] }),
          appliedPromoCodes.length > 0 && /* @__PURE__ */ jsx7(
            "div",
            {
              className: "flex flex-shrink",
              title: appliedPromoCodes.join(", ")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs4("div", { className: "flex flex-1 justify-between", children: [
          /* @__PURE__ */ jsxs4("div", { className: "flex flex-grow items-center gap-2", children: [
            /* @__PURE__ */ jsx7(
              Form.Field,
              {
                control: form.control,
                name: `outbound_items.${index}.quantity`,
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs4(Form.Item, { children: [
                    /* @__PURE__ */ jsx7(Form.Control, { children: /* @__PURE__ */ jsx7(
                      Input2,
                      {
                        ...field,
                        className: "bg-ui-bg-base txt-small w-[67px] rounded-lg",
                        min: 1,
                        type: "number",
                        "data-testid": `exchange-outbound-item-${previewItem.id}-qty`,
                        onBlur: (e) => {
                          const val = e.target.value;
                          const payload = val === "" ? null : Number(val);
                          field.onChange(payload);
                          if (payload) {
                            onUpdate({ quantity: payload });
                          }
                        }
                      }
                    ) }),
                    /* @__PURE__ */ jsx7(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx7(Text4, { className: "txt-small text-ui-fg-subtle", children: t("fields.qty") })
          ] }),
          /* @__PURE__ */ jsx7("div", { className: "text-ui-fg-subtle txt-small mr-2 flex flex-shrink-0", children: /* @__PURE__ */ jsx7(
            MoneyAmountCell,
            {
              currencyCode,
              amount: previewItem.total ?? 0
            }
          ) }),
          /* @__PURE__ */ jsx7(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    {
                      label: t("actions.remove"),
                      onClick: onRemove,
                      icon: /* @__PURE__ */ jsx7(XCircle2, {})
                    }
                  ]
                }
              ]
            }
          )
        ] })
      ] })
    }
  );
}

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-outbound-section.tsx
import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
var offersToAdd = [];
var offersToRemove = [];
var ExchangeOutboundSection = ({
  order,
  preview,
  exchange,
  form
}) => {
  const { t } = useTranslation10();
  const { setIsOpen } = useStackedModal();
  const { mutateAsync: addOutboundShipping } = useAddExchangeOutboundShipping(
    exchange.id,
    order.id
  );
  const { mutateAsync: addOutboundItem } = useAddExchangeOutboundItems(
    exchange.id,
    order.id
  );
  const { mutateAsync: updateOutboundItem } = useUpdateExchangeOutboundItem(
    exchange.id,
    order.id
  );
  const { mutateAsync: removeOutboundItem } = useRemoveExchangeOutboundItem(
    exchange.id,
    order.id
  );
  const previewOutboundItems = useMemo6(
    () => (preview?.items ?? []).filter(
      (i) => !!i.actions?.find(
        (a) => a.exchange_id === exchange.id && a.action === "ITEM_ADD"
      )
    ),
    [preview.items, exchange.id]
  );
  const {
    fields: outboundItems,
    append,
    remove,
    update
  } = useFieldArray2({
    name: "outbound_items",
    control: form.control
  });
  const previewItemsMap = useMemo6(
    () => new Map(previewOutboundItems.map((i) => [i.id, i])),
    [previewOutboundItems]
  );
  useEffect2(() => {
    const existingItemsMap = {};
    previewOutboundItems.forEach((i) => {
      const ind = outboundItems.findIndex((field) => field.item_id === i.id);
      const requested = i.detail?.quantity ?? 0;
      existingItemsMap[i.id] = true;
      if (ind > -1) {
        if (outboundItems[ind].quantity !== requested) {
          update(ind, {
            ...outboundItems[ind],
            quantity: requested
          });
        }
      } else {
        append(
          {
            item_id: i.id,
            quantity: requested,
            variant_id: i.variant_id ?? void 0
          },
          { shouldFocus: false }
        );
      }
    });
    outboundItems.forEach((i, ind) => {
      if (!(i.item_id in existingItemsMap)) {
        remove(ind);
      }
    });
  }, [previewOutboundItems]);
  const showOutboundItemsPlaceholder = !outboundItems.length;
  const onItemsSelected = async () => {
    if (offersToAdd.length) {
      await addOutboundItem(
        {
          // Vendor route resolves `offer_id` server-side.
          items: offersToAdd.map((offer_id) => ({
            offer_id,
            quantity: 1
          }))
        },
        {
          onError: (error) => {
            toast2.error(error.message);
          }
        }
      );
    }
    for (const offerToRemove of offersToRemove) {
      const field = outboundItems.find(
        (f) => f.offer_id === offerToRemove
      );
      const previewMatch = field ? previewOutboundItems.find((i) => i.id === field.item_id) : void 0;
      const actionId = previewMatch?.actions?.find(
        (a) => a.action === "ITEM_ADD"
      )?.id;
      if (actionId) {
        await removeOutboundItem(actionId, {
          onError: (error) => {
            toast2.error(error.message);
          }
        });
      }
    }
    setIsOpen("outbound-items", false);
  };
  useEffect2(() => {
    const outboundShipping = (preview.shipping_methods ?? []).find(
      (s) => !!s.actions?.find((a) => a.action === "SHIPPING_ADD" && !a.return_id)
    );
    if (outboundShipping?.shipping_option_id) {
      form.setValue("outbound_option_id", outboundShipping.shipping_option_id);
    } else {
      form.setValue("outbound_option_id", "");
    }
  }, [preview.shipping_methods]);
  const onShippingOptionChange = async (selectedOptionId) => {
    if (selectedOptionId) {
      await addOutboundShipping(
        { shipping_option_id: selectedOptionId },
        {
          onError: (error) => {
            toast2.error(error.message);
          }
        }
      );
    }
  };
  return /* @__PURE__ */ jsxs5("div", { children: [
    /* @__PURE__ */ jsxs5("div", { className: "mt-8 flex items-center justify-between", children: [
      /* @__PURE__ */ jsx8(Heading2, { level: "h2", children: t("orders.returns.outbound") }),
      /* @__PURE__ */ jsxs5(StackedFocusModal, { id: "outbound-items", children: [
        /* @__PURE__ */ jsx8(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx8(
          "a",
          {
            href: "#",
            onClick: (e) => e.preventDefault(),
            className: "focus-visible:shadow-borders-focus transition-fg txt-compact-small-plus cursor-pointer text-blue-500 outline-none hover:text-blue-400",
            children: t("actions.addItems")
          }
        ) }),
        /* @__PURE__ */ jsxs5(StackedFocusModal.Content, { children: [
          /* @__PURE__ */ jsx8(StackedFocusModal.Header, {}),
          /* @__PURE__ */ jsx8(
            AddExchangeOutboundItemsTable,
            {
              selectedItems: outboundItems.map((i) => i.offer_id).filter(Boolean),
              currencyCode: order.currency_code,
              onSelectionChange: (finalSelection) => {
                const alreadySelected = outboundItems.map((i) => i.offer_id).filter(Boolean);
                offersToAdd = finalSelection.filter(
                  (selection) => !alreadySelected.includes(selection)
                );
                offersToRemove = alreadySelected.filter(
                  (selection) => !finalSelection.includes(selection)
                );
              }
            }
          ),
          /* @__PURE__ */ jsx8(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsx8("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs5("div", { className: "flex items-center justify-end gap-x-2", children: [
            /* @__PURE__ */ jsx8(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx8(Button2, { type: "button", variant: "secondary", size: "small", children: t("actions.cancel") }) }),
            /* @__PURE__ */ jsx8(
              Button2,
              {
                type: "submit",
                variant: "primary",
                size: "small",
                onClick: async () => await onItemsSelected(),
                children: t("actions.save")
              },
              "submit-button"
            )
          ] }) }) })
        ] })
      ] })
    ] }),
    showOutboundItemsPlaceholder && /* @__PURE__ */ jsx8(ItemPlaceholder, {}),
    outboundItems.map((item, index) => {
      const previewItem = previewItemsMap.get(item.item_id);
      if (!previewItem) {
        return null;
      }
      return /* @__PURE__ */ jsx8(
        ExchangeOutboundItem,
        {
          previewItem,
          currencyCode: order.currency_code,
          form,
          onRemove: () => {
            const actionId = previewOutboundItems.find((i) => i.id === item.item_id)?.actions?.find((a) => a.action === "ITEM_ADD")?.id;
            if (actionId) {
              removeOutboundItem(actionId, {
                onError: (error) => {
                  toast2.error(error.message);
                }
              });
            }
          },
          onUpdate: (payload) => {
            const actionId = previewOutboundItems.find((i) => i.id === item.item_id)?.actions?.find((a) => a.action === "ITEM_ADD")?.id;
            if (actionId) {
              updateOutboundItem(
                { $actionId: actionId, ...payload },
                {
                  onError: (error) => {
                    toast2.error(error.message);
                  }
                }
              );
            }
          },
          index
        },
        item.id
      );
    }),
    !showOutboundItemsPlaceholder && /* @__PURE__ */ jsx8("div", { className: "mt-8 flex flex-col gap-y-4", children: /* @__PURE__ */ jsxs5("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
      /* @__PURE__ */ jsxs5("div", { children: [
        /* @__PURE__ */ jsx8(Form.Label, { children: t("orders.exchanges.outboundShipping") }),
        /* @__PURE__ */ jsx8(Form.Hint, { className: "!mt-1", children: t("orders.exchanges.outboundShippingHint") })
      ] }),
      /* @__PURE__ */ jsx8(
        Form.Field,
        {
          control: form.control,
          name: "outbound_option_id",
          render: ({ field: { value, onChange, ...field } }) => {
            return /* @__PURE__ */ jsx8(Form.Item, { children: /* @__PURE__ */ jsx8(Form.Control, { children: /* @__PURE__ */ jsx8(
              Combobox,
              {
                allowClear: true,
                value: value ?? void 0,
                onChange: (val) => {
                  onChange(val);
                  onShippingOptionChange(val);
                },
                ...field,
                options: [],
                disabled: true
              }
            ) }) });
          }
        }
      )
    ] }) })
  ] });
};

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/schema.ts
import { z } from "zod";
var ExchangeCreateSchema = z.object({
  inbound_items: z.array(
    z.object({
      item_id: z.string(),
      variant_id: z.string().nullish(),
      quantity: z.number(),
      reason_id: z.string().nullish(),
      note: z.string().nullish()
    })
  ),
  outbound_items: z.array(
    z.object({
      item_id: z.string(),
      offer_id: z.string().nullish(),
      variant_id: z.string().nullish(),
      quantity: z.number()
    })
  ),
  location_id: z.string().optional(),
  inbound_option_id: z.string().nullish(),
  outbound_option_id: z.string().nullish(),
  send_notification: z.boolean().optional()
});

// src/pages/orders/[id]/exchanges/create/_components/exchange-create-form/exchange-create-form.tsx
import { Fragment, jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
var readExchangeId = (change) => {
  if (change && typeof change === "object" && "exchange_id" in change && typeof change.exchange_id === "string") {
    return change.exchange_id;
  }
  return void 0;
};
var IS_REQUEST_RUNNING = false;
var ExchangeCreateForm = () => {
  const { id } = useParams();
  const { t } = useTranslation11();
  const navigate = useNavigate();
  const { handleSuccess } = useRouteModal();
  const orderId = id ?? "";
  const { order } = useOrder(orderId, {
    fields: "currency_code,total,items.*,items.variant.*"
  });
  const { order: preview } = useOrderPreview(orderId);
  const [exchangeId, setExchangeId] = useState3("");
  const [submitting, setSubmitting] = useState3(false);
  const [canceling, setCanceling] = useState3(false);
  const form = useForm({
    defaultValues: {
      inbound_items: [],
      outbound_items: [],
      location_id: void 0,
      inbound_option_id: null,
      outbound_option_id: null,
      send_notification: false
    },
    resolver: zodResolver(ExchangeCreateSchema)
  });
  const { mutateAsync: createExchange } = useCreateExchange(orderId);
  const { mutateAsync: cancelBegin } = useCancelExchangeBegin(
    exchangeId,
    orderId
  );
  const { mutateAsync: requestExchange, isPending: isConfirming } = useRequestExchange(exchangeId, orderId);
  useEffect3(() => {
    async function run() {
      if (IS_REQUEST_RUNNING || exchangeId || !preview) {
        return;
      }
      if (preview.order_change) {
        if (preview.order_change.change_type !== "exchange") {
          navigate(`/orders/${orderId}`, { replace: true });
          toast3.error(t("orders.exchanges.activeChangeError"));
          return;
        }
        const existingExchangeId = readExchangeId(preview.order_change);
        if (existingExchangeId) {
          setExchangeId(existingExchangeId);
        }
        return;
      }
      IS_REQUEST_RUNNING = true;
      try {
        const { exchange } = await createExchange({ order_id: orderId });
        setExchangeId(exchange.id);
      } catch (e) {
        toast3.error(
          e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
        );
        navigate(`/orders/${orderId}`, { replace: true });
      } finally {
        IS_REQUEST_RUNNING = false;
      }
    }
    run();
  }, [preview, orderId, exchangeId]);
  const inboundItemsWatch = form.watch("inbound_items");
  const outboundItemsWatch = form.watch("outbound_items");
  const hasSelection = useMemo7(
    () => (inboundItemsWatch?.length ?? 0) > 0 || (outboundItemsWatch?.length ?? 0) > 0,
    [inboundItemsWatch, outboundItemsWatch]
  );
  const previewItems = useMemo7(() => {
    if (!exchangeId) return [];
    return (preview?.items ?? []).filter(
      (i) => !!i.actions?.find((a) => a.exchange_id === exchangeId)
    );
  }, [preview, exchangeId]);
  const inboundPreviewItems = useMemo7(
    () => previewItems.filter(
      (item) => !!item.actions?.find((a) => a.action === "RETURN_ITEM")
    ),
    [previewItems]
  );
  const outboundPreviewItems = useMemo7(
    () => previewItems.filter(
      (item) => !!item.actions?.find((a) => a.action === "ITEM_ADD")
    ),
    [previewItems]
  );
  const currencyCode = order?.currency_code ?? "";
  const inboundTotal = useMemo7(() => {
    return inboundPreviewItems.reduce((acc, item) => {
      const action = item.actions?.find((a) => a.action === "RETURN_ITEM");
      const requested = Number(action?.details?.quantity || 0);
      const itemQty = item.quantity ?? 0;
      const itemTotal = item.total ?? 0;
      if (!itemQty) return acc;
      return acc + requested / itemQty * itemTotal;
    }, 0);
  }, [inboundPreviewItems]);
  const outboundTotal = useMemo7(() => {
    return outboundPreviewItems.reduce(
      (acc, item) => acc + (item.total ?? 0),
      0
    );
  }, [outboundPreviewItems]);
  const inboundShippingTotal = useMemo7(() => {
    const methods = preview?.shipping_methods ?? [];
    const method = methods.find(
      (sm) => !!sm.actions?.find((a) => a.action === "SHIPPING_ADD" && !!a.return_id)
    );
    return method?.total ?? 0;
  }, [preview]);
  const outboundShippingTotal = useMemo7(() => {
    const methods = preview?.shipping_methods ?? [];
    const method = methods.find(
      (sm) => !!sm.actions?.find((a) => a.action === "SHIPPING_ADD" && !a.return_id)
    );
    return method?.total ?? 0;
  }, [preview]);
  const estimatedDifference = useMemo7(() => {
    const summary = preview?.summary;
    return (summary?.pending_difference ?? 0) - inboundTotal;
  }, [preview, inboundTotal]);
  const prompt = usePrompt();
  const handleSubmit = form.handleSubmit(async (data) => {
    if (!exchangeId) {
      return;
    }
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("orders.exchanges.confirmText"),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel"),
      variant: "confirmation"
    });
    if (!res) {
      return;
    }
    setSubmitting(true);
    try {
      await requestExchange(
        { no_notification: !data.send_notification }
      );
      toast3.success(t("orders.exchanges.toast.confirmedSuccessfully"));
      handleSuccess(`/orders/${orderId}`);
    } catch (e) {
      toast3.error(t("general.error"), {
        description: e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      });
    } finally {
      setSubmitting(false);
    }
  });
  const handleClose = async () => {
    if (!exchangeId) {
      navigate(`/orders/${orderId}`, { replace: true });
      return;
    }
    setCanceling(true);
    try {
      await cancelBegin();
      toast3.success(t("orders.exchanges.toast.canceledSuccessfully"));
    } catch {
    } finally {
      setCanceling(false);
      navigate(`/orders/${orderId}`, { replace: true });
    }
  };
  const ready = !!order && !!preview && !!exchangeId;
  return /* @__PURE__ */ jsx9(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs6(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsx9(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx9(RouteFocusModal.Body, { className: "flex size-full justify-center overflow-y-auto", children: /* @__PURE__ */ jsxs6("div", { className: "mt-16 w-[720px] max-w-[100%] px-4 md:p-0", children: [
      /* @__PURE__ */ jsx9(Heading3, { level: "h1", children: t("orders.exchanges.create") }),
      /* @__PURE__ */ jsx9(Text5, { size: "small", className: "text-ui-fg-subtle mt-2", children: t("orders.exchanges.policyHint", {
        days: EXCHANGE_POLICY_DAYS
      }) }),
      ready && /* @__PURE__ */ jsxs6(Fragment, { children: [
        /* @__PURE__ */ jsx9(
          ExchangeInboundSection,
          {
            form,
            preview,
            order,
            exchange: { id: exchangeId }
          }
        ),
        /* @__PURE__ */ jsx9(
          ExchangeOutboundSection,
          {
            form,
            preview,
            order,
            exchange: { id: exchangeId }
          }
        ),
        /* @__PURE__ */ jsxs6("div", { className: "mt-8 border-y border-dotted py-4", children: [
          /* @__PURE__ */ jsxs6("div", { className: "mb-2 flex items-center justify-between", children: [
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.returns.inboundTotal") }),
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(-1 * inboundTotal, currencyCode) })
          ] }),
          /* @__PURE__ */ jsxs6("div", { className: "mb-2 flex items-center justify-between", children: [
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.exchanges.outboundTotal") }),
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(outboundTotal, currencyCode) })
          ] }),
          /* @__PURE__ */ jsxs6("div", { className: "mb-2 flex items-center justify-between", children: [
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.returns.inboundShipping") }),
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(inboundShippingTotal, currencyCode) })
          ] }),
          /* @__PURE__ */ jsxs6("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.exchanges.outboundShipping") }),
            /* @__PURE__ */ jsx9("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(outboundShippingTotal, currencyCode) })
          ] }),
          /* @__PURE__ */ jsxs6("div", { className: "mt-4 flex items-center justify-between border-t border-dotted pt-4", children: [
            /* @__PURE__ */ jsx9("span", { className: "txt-small font-medium", children: t("orders.exchanges.refundAmount") }),
            /* @__PURE__ */ jsx9("span", { className: "txt-small font-medium", children: getStylizedAmount(estimatedDifference, currencyCode) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx9("div", { className: "bg-ui-bg-field mt-8 rounded-lg border py-2 pl-2 pr-4", children: /* @__PURE__ */ jsx9(
        Form.Field,
        {
          control: form.control,
          name: "send_notification",
          render: ({ field: { onChange, value, ...field } }) => /* @__PURE__ */ jsxs6(Form.Item, { children: [
            /* @__PURE__ */ jsxs6("div", { className: "flex items-center", children: [
              /* @__PURE__ */ jsx9(Form.Control, { className: "mr-4 self-start", children: /* @__PURE__ */ jsx9(
                Switch,
                {
                  dir: "ltr",
                  className: "mt-[2px] rtl:rotate-180",
                  checked: !!value,
                  onCheckedChange: onChange,
                  ...field,
                  "data-testid": "exchange-create-notify"
                }
              ) }),
              /* @__PURE__ */ jsxs6("div", { className: "block", children: [
                /* @__PURE__ */ jsx9(Form.Label, { children: t("orders.returns.sendNotification") }),
                /* @__PURE__ */ jsx9(Form.Hint, { className: "!mt-1", children: t("orders.returns.sendNotificationHint") })
              ] })
            ] }),
            /* @__PURE__ */ jsx9(Form.ErrorMessage, {})
          ] })
        }
      ) }),
      /* @__PURE__ */ jsx9("div", { className: "p-8" })
    ] }) }),
    /* @__PURE__ */ jsx9(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsx9("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs6("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx9(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx9(
        Button3,
        {
          type: "button",
          onClick: handleClose,
          variant: "secondary",
          size: "small",
          isLoading: canceling,
          disabled: submitting,
          "data-testid": "exchange-cancel",
          children: t("orders.exchanges.cancel.title")
        }
      ) }),
      /* @__PURE__ */ jsx9(
        Button3,
        {
          type: "submit",
          variant: "primary",
          size: "small",
          isLoading: submitting || isConfirming,
          disabled: !exchangeId || canceling || !hasSelection,
          "data-testid": "exchange-confirm",
          children: t("orders.exchanges.confirm")
        },
        "submit-button"
      )
    ] }) }) })
  ] }) });
};

// src/pages/orders/[id]/exchanges/create/index.tsx
import { jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
var Component = () => {
  const { t } = useTranslation12();
  return /* @__PURE__ */ jsxs7(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx10(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx10("span", { className: "sr-only", children: t("orders.exchanges.title") }) }),
    /* @__PURE__ */ jsx10(RouteFocusModal.Description, { className: "sr-only", children: t("orders.exchanges.title") }),
    /* @__PURE__ */ jsx10(ExchangeCreateForm, {})
  ] });
};
var create_default = Component;
export {
  Component,
  create_default as default
};
