import {
  ItemPlaceholder
} from "./chunk-ZHFFTT3I.js";
import {
  ReturnShippingPlaceholder
} from "./chunk-YBF45CX5.js";
import {
  useReturnReasons
} from "./chunk-65HHU6D3.js";
import {
  useAddClaimInboundItems,
  useAddClaimInboundShipping,
  useCancelClaimRequest,
  useClaim,
  useClaimConfirmRequest,
  useCreateClaim,
  useDeleteClaimInboundShipping,
  useRemoveClaimInboundItem,
  useUpdateClaimInboundItem,
  useUpdateClaimInboundShipping
} from "./chunk-D6RN3ONJ.js";
import {
  getReturnableQuantity
} from "./chunk-UM7ZR3VU.js";
import {
  DEFAULT_FIELDS
} from "./chunk-IMJ62GAP.js";
import {
  useReturn,
  useUpdateReturn
} from "./chunk-OQTL7PXK.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]/claims/create/index.tsx
import { toast as toast2 } from "@medusajs/ui";
import { useEffect as useEffect2, useState as useState4 } from "react";
import { useTranslation as useTranslation11 } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";

// src/pages/orders/[id]/claims/create/_components/claim-create-form/claim-create-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Alert, Button as Button2, Heading as Heading2, Switch, Text as Text4, toast, usePrompt } from "@medusajs/ui";
import { useEffect, useMemo as useMemo5, useState as useState3 } from "react";
import { useFieldArray as useFieldArray2, useForm } from "react-hook-form";
import { useTranslation as useTranslation10 } from "react-i18next";

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

// src/pages/orders/[id]/claims/create/_components/add-claim-items-table/use-claim-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 useClaimItemTableColumns = (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]/claims/create/_components/add-claim-items-table/use-claim-item-table-filters.tsx
import { useTranslation as useTranslation2 } from "react-i18next";
var useClaimItemTableFilters = () => {
  const { t } = useTranslation2();
  const filters = [
    {
      key: "returnable_quantity",
      label: t("orders.returns.returnableQuantityLabel"),
      type: "number"
    },
    {
      key: "refundable_amount",
      label: t("orders.returns.refundableAmountLabel"),
      type: "number"
    },
    {
      key: "created_at",
      label: t("fields.createdAt"),
      type: "date"
    },
    {
      key: "updated_at",
      label: t("fields.updatedAt"),
      type: "date"
    }
  ];
  return filters;
};

// src/pages/orders/[id]/claims/create/_components/add-claim-items-table/use-claim-item-table-query.tsx
var useClaimItemTableQuery = ({
  pageSize = 50,
  prefix
}) => {
  const raw = useQueryParams(
    [
      "q",
      "offset",
      "order",
      "created_at",
      "updated_at",
      "returnable_quantity",
      "refundable_amount"
    ],
    prefix
  );
  const {
    offset,
    created_at,
    updated_at,
    refundable_amount,
    returnable_quantity,
    ...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,
    refundable_amount: refundable_amount ? JSON.parse(refundable_amount) : void 0,
    returnable_quantity: returnable_quantity ? JSON.parse(returnable_quantity) : void 0
  };
  return { searchParams, raw };
};

// src/pages/orders/[id]/claims/create/_components/add-claim-items-table/add-claim-items-table.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 50;
var PREFIX = "rit";
var AddClaimItemsTable = ({
  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 } = useClaimItemTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const queriedItems = useMemo2(() => {
    const {
      order,
      offset,
      limit,
      q,
      created_at,
      updated_at,
      refundable_amount,
      returnable_quantity
    } = 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");
    }
    if (returnable_quantity) {
      results = filterByNumber(
        results,
        returnable_quantity,
        "returnable_quantity",
        currencyCode
      );
    }
    if (refundable_amount) {
      results = filterByNumber(
        results,
        refundable_amount,
        "refundable_amount",
        currencyCode
      );
    }
    return results.slice(offset, offset + limit);
  }, [items, currencyCode, searchParams]);
  const columns = useClaimItemTableColumns(currencyCode);
  const filters = useClaimItemTableFilters();
  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",
      "data-testid": "add-claim-items-picker",
      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") },
            {
              key: "returnable_quantity",
              label: t("orders.fields.returnableQuantity")
            },
            {
              key: "refundable_amount",
              label: t("orders.fields.refundableAmount")
            }
          ],
          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;
    } else if (field === "returnable_quantity") {
      aValue = getReturnableQuantity(a);
      bValue = getReturnableQuantity(b);
    } else if (field === "refundable_amount") {
      aValue = a.refundable_total ?? 0;
      bValue = b.refundable_total ?? 0;
    }
    if (aValue === void 0 || aValue === null) return 1;
    if (bValue === void 0 || bValue === null) return -1;
    if (aValue < bValue) {
      return direction === "asc" ? -1 : 1;
    }
    if (aValue > bValue) {
      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;
  });
};
var defaultOperators = {
  eq: void 0,
  gt: void 0,
  gte: void 0,
  lt: void 0,
  lte: void 0
};
var filterByNumber = (items, value, field, currency_code) => {
  const { eq, gt, lt, gte, lte } = typeof value === "object" ? { ...defaultOperators, ...value } : { ...defaultOperators, eq: value };
  return items.filter((i) => {
    const returnableQuantity = getReturnableQuantity(i);
    const refundableAmount = getStylizedAmount(
      i.refundable_total ?? 0,
      currency_code
    );
    const itemValue = field === "returnable_quantity" ? returnableQuantity : refundableAmount;
    if (eq !== void 0) {
      return itemValue === eq;
    }
    let isValid = true;
    if (gt !== void 0) {
      isValid = isValid && Number(itemValue) > gt;
    }
    if (gte !== void 0) {
      isValid = isValid && Number(itemValue) >= gte;
    }
    if (lt !== void 0) {
      isValid = isValid && Number(itemValue) < lt;
    }
    if (lte !== void 0) {
      isValid = isValid && Number(itemValue) <= lte;
    }
    return isValid;
  });
};

// src/pages/orders/[id]/claims/create/_components/claim-create-form/claim-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 { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
function ClaimInboundItem({
  item,
  previewItem,
  currencyCode,
  form,
  onRemove,
  onUpdate,
  index
}) {
  const { t } = useTranslation4();
  const { return_reasons = [] } = useReturnReasons({ fields: "+label" });
  const formItem = form.watch(`inbound_items.${index}`);
  const showReturnReason = typeof formItem.reason_id === "string";
  const showNote = typeof formItem.note === "string";
  return /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl ", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-x-2 gap-y-2 border-b 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-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 })
        ] })
      ] }),
      /* @__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",
                      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
          }
        ) }),
        /* @__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)
              }
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Fragment, { children: [
      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: { ref: _ref, value, onChange, ...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,
                      onChange: (v) => {
                        onUpdate({ reason_id: v });
                        onChange(v);
                      },
                      ...field,
                      options: return_reasons.map((reason) => ({
                        label: reason.label ?? "",
                        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, ...field } }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx3(Form.Control, { children: /* @__PURE__ */ jsx3(
                    Input,
                    {
                      ...field,
                      value: field.value ?? "",
                      onBlur: () => {
                        field.onChange(field.value);
                        onUpdate({ internal_note: field.value });
                      },
                      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" })
            }
          )
        ] })
      ] })
    ] })
  ] });
}

// src/pages/orders/[id]/claims/create/_components/claim-create-form/claim-outbound-section.tsx
import { Button, Heading } from "@medusajs/ui";
import { useFieldArray } from "react-hook-form";
import { useTranslation as useTranslation9 } from "react-i18next";

// src/pages/orders/[id]/claims/create/_components/add-claim-outbound-items-table/add-claim-outbound-items-table.tsx
import { useMemo as useMemo4, useState as useState2 } from "react";
import { useTranslation as useTranslation7 } from "react-i18next";

// src/pages/orders/[id]/claims/create/_components/add-claim-outbound-items-table/use-claim-outbound-item-table-columns.tsx
import { Checkbox as Checkbox2, Text as Text2 } from "@medusajs/ui";
import { createColumnHelper as createColumnHelper2 } from "@tanstack/react-table";
import { useMemo as useMemo3 } from "react";
import { useTranslation as useTranslation5 } from "react-i18next";
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
var columnHelper2 = createColumnHelper2();
var useClaimOutboundItemTableColumns = () => {
  const { t } = useTranslation5();
  return useMemo3(
    () => [
      columnHelper2.display({
        id: "select",
        header: ({ table }) => /* @__PURE__ */ jsx4(
          Checkbox2,
          {
            checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
            onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
          }
        ),
        cell: ({ row }) => {
          const isSelectable = row.getCanSelect();
          return /* @__PURE__ */ jsx4(
            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__ */ jsx4(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsxs2("div", { className: "flex h-full w-full max-w-[300px] items-center gap-x-3 overflow-hidden", children: [
            /* @__PURE__ */ jsx4(Thumbnail, { src: variant?.product?.thumbnail }),
            /* @__PURE__ */ jsx4(
              Text2,
              {
                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__ */ jsx4(PlaceholderCell, {});
          return /* @__PURE__ */ jsx4(Text2, { 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__ */ jsx4(PlaceholderCell, {});
          return /* @__PURE__ */ jsx4(Text2, { size: "small", leading: "compact", className: "truncate", children: title });
        }
      })
    ],
    [t]
  );
};

// src/pages/orders/[id]/claims/create/_components/add-claim-outbound-items-table/use-claim-outbound-item-table-filters.tsx
import { useTranslation as useTranslation6 } from "react-i18next";
var useClaimOutboundItemTableFilters = () => {
  const { t } = useTranslation6();
  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]/claims/create/_components/add-claim-outbound-items-table/use-claim-outbound-item-table-query.tsx
var useClaimOutboundItemTableQuery = ({
  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]/claims/create/_components/add-claim-outbound-items-table/add-claim-outbound-items-table.tsx
import { jsx as jsx5 } 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 AddClaimOutboundItemsTable = ({
  currencyCode,
  onSelectionChange
}) => {
  const { t } = useTranslation7();
  const [rowSelection, setRowSelection] = useState2({});
  const [offerLookup, setOfferLookup] = useState2({});
  const updater = (fn) => {
    const newState = typeof fn === "function" ? fn(rowSelection) : fn;
    setRowSelection(newState);
    onSelectionChange(Object.keys(newState), offerLookup);
  };
  const { searchParams, raw } = useClaimOutboundItemTableQuery({
    pageSize: PAGE_SIZE2,
    prefix: PREFIX2
  });
  const offersResponse = useOffers({
    ...searchParams,
    fields: OFFER_PICKER_FIELDS
  });
  const rawOffersSource = offersResponse.offers;
  const rawOffers = useMemo4(
    () => rawOffersSource ?? [],
    [rawOffersSource]
  );
  const offers = useMemo4(() => {
    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]);
  useMemo4(() => {
    if (!offers.length) return;
    setOfferLookup((prev) => {
      let changed = false;
      const next = { ...prev };
      for (const offer of offers) {
        if (!next[offer.id]) {
          next[offer.id] = offer;
          changed = true;
        }
      }
      return changed ? next : prev;
    });
  }, [offers]);
  const count = offers.length;
  const columns = useClaimOutboundItemTableColumns();
  const filters = useClaimOutboundItemTableFilters();
  const { table } = useDataTable({
    data: offers,
    columns,
    count,
    enablePagination: true,
    // Row id = offer id so onSelectionChange yields offer_ids that the form
    // layer sends to `useAddClaimOutboundItems` (which accepts `offer_id` and
    // resolves to variant_id + unit_price server-side).
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE2,
    enableRowSelection: () => true,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx5(
    "div",
    {
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "add-claim-outbound-picker",
      children: /* @__PURE__ */ jsx5(
        _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]/claims/create/_components/claim-create-form/claim-outbound-item.tsx
import { XCircle as XCircle2 } from "@medusajs/icons";
import { Input as Input2, Text as Text3 } from "@medusajs/ui";
import { useTranslation as useTranslation8 } from "react-i18next";
import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
function ClaimOutboundItem({
  form,
  onRemove,
  index
}) {
  const { t } = useTranslation8();
  const row = form.watch(`outbound_items.${index}`);
  const productTitle = row?.product_title ?? row?.variant_title ?? row?.offer_id;
  return /* @__PURE__ */ jsx6(
    "div",
    {
      className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl",
      "data-testid": `claim-outbound-item-${row?.offer_id ?? index}`,
      children: /* @__PURE__ */ jsxs3("div", { className: "flex flex-col items-center gap-x-2 gap-y-2 border-b p-3 text-sm md:flex-row", children: [
        /* @__PURE__ */ jsxs3("div", { className: "flex flex-1 items-center gap-x-3", children: [
          /* @__PURE__ */ jsx6(Thumbnail, { src: row?.thumbnail ?? void 0 }),
          /* @__PURE__ */ jsxs3("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsxs3("div", { children: [
              /* @__PURE__ */ jsxs3(Text3, { className: "txt-small", as: "span", weight: "plus", children: [
                productTitle,
                " "
              ] }),
              row?.sku && /* @__PURE__ */ jsxs3("span", { children: [
                "(",
                row.sku,
                ")"
              ] })
            ] }),
            row?.variant_title && /* @__PURE__ */ jsx6(Text3, { as: "div", className: "text-ui-fg-subtle txt-small", children: row.variant_title })
          ] })
        ] }),
        /* @__PURE__ */ jsxs3("div", { className: "flex flex-1 justify-between", children: [
          /* @__PURE__ */ jsxs3("div", { className: "flex flex-grow items-center gap-2", children: [
            /* @__PURE__ */ jsx6(
              Form.Field,
              {
                control: form.control,
                name: `outbound_items.${index}.quantity`,
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs3(Form.Item, { children: [
                    /* @__PURE__ */ jsx6(Form.Control, { children: /* @__PURE__ */ jsx6(
                      Input2,
                      {
                        ...field,
                        className: "bg-ui-bg-base txt-small w-[67px] rounded-lg",
                        min: 1,
                        type: "number",
                        onBlur: (e) => {
                          const val = e.target.value;
                          const payload = val === "" ? null : Number(val);
                          field.onChange(payload);
                        }
                      }
                    ) }),
                    /* @__PURE__ */ jsx6(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx6(Text3, { className: "txt-small text-ui-fg-subtle", children: t("fields.qty") })
          ] }),
          /* @__PURE__ */ jsx6(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    {
                      label: t("actions.remove"),
                      onClick: onRemove,
                      icon: /* @__PURE__ */ jsx6(XCircle2, {})
                    }
                  ]
                }
              ]
            }
          )
        ] })
      ] })
    }
  );
}

// src/pages/orders/[id]/claims/create/_components/claim-create-form/claim-outbound-section.tsx
import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
var STACKED_MODAL_ID = "claim-add-outbound-items";
var ClaimOutboundSection = ({
  form,
  currencyCode,
  disabled
}) => {
  const { t } = useTranslation9();
  const { setIsOpen } = useStackedModal();
  const {
    fields: outboundItems,
    append,
    remove
  } = useFieldArray({
    name: "outbound_items",
    control: form.control
  });
  const showOutboundItemsPlaceholder = !outboundItems.length;
  const onItemsSelected = (selectedOfferIds, offerLookup) => {
    const existing = new Set(outboundItems.map((row) => row.offer_id));
    selectedOfferIds.filter((id) => !existing.has(id)).forEach((id) => {
      const offer = offerLookup[id];
      const variant = offer?.product_variant;
      append(
        {
          offer_id: id,
          variant_id: offer?.variant_id ?? variant?.id ?? null,
          product_title: variant?.product?.title ?? null,
          variant_title: variant?.title ?? null,
          thumbnail: variant?.product?.thumbnail ?? null,
          sku: offer?.sku ?? null,
          quantity: 1
        },
        { shouldFocus: false }
      );
    });
    setIsOpen(STACKED_MODAL_ID, false);
  };
  return /* @__PURE__ */ jsxs4("div", { children: [
    /* @__PURE__ */ jsxs4("div", { className: "mt-8 flex items-center justify-between", children: [
      /* @__PURE__ */ jsx7(Heading, { level: "h2", children: t("orders.claims.outboundItems") }),
      /* @__PURE__ */ jsxs4(StackedFocusModal, { id: STACKED_MODAL_ID, children: [
        /* @__PURE__ */ jsx7(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx7(
          "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",
            "data-testid": "claim-add-outbound-trigger",
            children: t("orders.claims.addOutboundItems")
          }
        ) }),
        /* @__PURE__ */ jsxs4(StackedFocusModal.Content, { children: [
          /* @__PURE__ */ jsx7(StackedFocusModal.Header, {}),
          /* @__PURE__ */ jsx7(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx7("span", { className: "sr-only", children: t("orders.claims.addOutboundItems") }) }),
          /* @__PURE__ */ jsx7(StackedFocusModal.Description, { className: "sr-only", children: t("orders.claims.addOutboundItemsDescription") }),
          /* @__PURE__ */ jsx7(StackedFocusModal.Body, { className: "size-full overflow-hidden", children: /* @__PURE__ */ jsx7(
            PickerBody,
            {
              currencyCode,
              onSubmit: onItemsSelected
            }
          ) })
        ] })
      ] })
    ] }),
    showOutboundItemsPlaceholder && /* @__PURE__ */ jsx7(ItemPlaceholder, {}),
    outboundItems.map((item, index) => /* @__PURE__ */ jsx7(
      ClaimOutboundItem,
      {
        form,
        index,
        onRemove: () => remove(index)
      },
      item.id
    )),
    /* @__PURE__ */ jsx7("span", { className: "sr-only", children: disabled ? "" : "" })
  ] });
};
var PickerBody = ({
  currencyCode,
  onSubmit
}) => {
  const { t } = useTranslation9();
  let selectedOfferIds = [];
  let selectedOfferLookup = {};
  return /* @__PURE__ */ jsxs4("div", { className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsx7("div", { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx7(
      AddClaimOutboundItemsTable,
      {
        currencyCode,
        onSelectionChange: (ids, lookup) => {
          selectedOfferIds = ids;
          selectedOfferLookup = lookup;
        }
      }
    ) }),
    /* @__PURE__ */ jsx7(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs4("div", { className: "flex w-full items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx7(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx7(
        Button,
        {
          type: "button",
          variant: "secondary",
          size: "small",
          "data-testid": "claim-add-outbound-cancel",
          children: t("actions.cancel")
        }
      ) }),
      /* @__PURE__ */ jsx7(
        Button,
        {
          type: "button",
          variant: "primary",
          size: "small",
          "data-testid": "claim-add-outbound-save",
          onClick: () => onSubmit(selectedOfferIds, selectedOfferLookup),
          children: t("actions.save")
        },
        "submit-button"
      )
    ] }) })
  ] });
};

// src/pages/orders/[id]/claims/create/_components/claim-create-form/schema.ts
import { z } from "zod";
var ClaimCreateSchema = 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({
      offer_id: z.string(),
      variant_id: z.string().nullish(),
      product_title: z.string().nullish(),
      variant_title: z.string().nullish(),
      thumbnail: z.string().nullish(),
      sku: z.string().nullish(),
      quantity: z.number()
    })
  ),
  location_id: z.string().nullish(),
  inbound_option_id: z.string().nullish(),
  outbound_option_id: z.string().nullish(),
  send_notification: z.boolean().optional()
});

// src/pages/orders/[id]/claims/create/_components/claim-create-form/claim-create-form.tsx
import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
var itemsToAdd = [];
var itemsToRemove = [];
var IS_CANCELING = false;
var ClaimCreateForm = ({
  order,
  preview,
  claim,
  orderReturn
}) => {
  const { t } = useTranslation10();
  const { handleSuccess } = useRouteModal();
  const { setIsOpen } = useStackedModal();
  const [_inventoryMap, setInventoryMap] = useState3({});
  const { mutateAsync: confirmClaimRequest, isPending: isConfirming } = useClaimConfirmRequest(claim.id, order.id);
  const { mutateAsync: cancelClaimRequest, isPending: isCanceling } = useCancelClaimRequest(claim.id, order.id);
  const { mutateAsync: updateReturn, isPending: isUpdating } = useUpdateReturn(
    preview?.order_change?.return_id ?? "",
    order.id
  );
  const {
    mutateAsync: addInboundShipping,
    isPending: isAddingInboundShipping
  } = useAddClaimInboundShipping(claim.id, order.id);
  const {
    mutateAsync: _updateInboundShipping,
    isPending: isUpdatingInboundShipping
  } = useUpdateClaimInboundShipping(claim.id, order.id);
  const {
    mutateAsync: deleteInboundShipping,
    isPending: isDeletingInboundShipping
  } = useDeleteClaimInboundShipping(claim.id, order.id);
  const { mutateAsync: addInboundItem, isPending: isAddingInboundItem } = useAddClaimInboundItems(claim.id, order.id);
  const { mutateAsync: updateInboundItem, isPending: isUpdatingInboundItem } = useUpdateClaimInboundItem(claim.id, order.id);
  const { mutateAsync: removeInboundItem, isPending: isRemovingInboundItem } = useRemoveClaimInboundItem(claim.id, order.id);
  const isRequestLoading = isConfirming || isCanceling || isAddingInboundShipping || isUpdatingInboundShipping || isDeletingInboundShipping || isAddingInboundItem || isRemovingInboundItem || isUpdatingInboundItem || isUpdating;
  const previewItems = useMemo5(
    () => preview?.items?.filter(
      (i) => !!i.actions?.find((a) => a.claim_id === claim.id)
    ) ?? [],
    [preview.items, claim.id]
  );
  const inboundPreviewItems = useMemo5(
    () => previewItems.filter(
      (item) => !!item.actions?.find((a) => a.action === "RETURN_ITEM")
    ),
    [previewItems]
  );
  const itemsMap = useMemo5(
    () => new Map(order?.items?.map((i) => [i.id, i])),
    [order.items]
  );
  const form = useForm({
    defaultValues: () => {
      const inboundShippingMethod = preview.shipping_methods?.find((s) => {
        return !!s.actions?.find(
          (a) => a.action === "SHIPPING_ADD" && !!a.return_id
        );
      });
      return Promise.resolve({
        inbound_items: inboundPreviewItems.map((i) => {
          const inboundAction = i.actions?.find(
            (a) => a.action === "RETURN_ITEM"
          );
          return {
            item_id: i.id,
            variant_id: i.variant_id,
            quantity: i.detail?.return_requested_quantity ?? 1,
            note: inboundAction?.internal_note,
            reason_id: inboundAction?.details?.reason_id
          };
        }),
        outbound_items: [],
        inbound_option_id: inboundShippingMethod ? inboundShippingMethod.shipping_option_id : null,
        outbound_option_id: null,
        location_id: orderReturn?.location_id ?? null,
        send_notification: false
      });
    },
    resolver: zodResolver(ClaimCreateSchema)
  });
  const locationId = form.watch("location_id");
  const { stock_locations: stockLocations = [] } = useStockLocations({
    limit: 999
  });
  const { shipping_options: shippingOptions = [] } = useShippingOptions(
    locationId ? {
      limit: 999,
      fields: "*prices,+service_zone.fulfillment_set.location.id",
      stock_location_id: locationId
    } : void 0,
    { enabled: !!locationId }
  );
  const inboundShippingOptions = (shippingOptions ?? []).filter(
    (so) => !!so.rules?.find(
      (r) => r.attribute === "is_return" && r.value === "true"
    )
  );
  const {
    fields: inboundItems,
    append,
    remove,
    update
  } = useFieldArray2({
    name: "inbound_items",
    control: form.control
  });
  const previewItemsMap = useMemo5(
    () => new Map(previewItems.map((i) => [i.id, i])),
    [previewItems]
  );
  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,
            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);
      }
    });
  }, [previewItems]);
  useEffect(() => {
    const inboundShipping = preview.shipping_methods?.find(
      (s) => !!s.actions?.find((a) => a.action === "SHIPPING_ADD" && !!a.return_id)
    );
    if (inboundShipping) {
      form.setValue("inbound_option_id", inboundShipping.shipping_option_id);
    } else {
      form.setValue("inbound_option_id", null);
    }
  }, [preview.shipping_methods]);
  useEffect(() => {
    form.setValue("location_id", orderReturn?.location_id ?? null);
  }, [orderReturn]);
  const showInboundItemsPlaceholder = !inboundPreviewItems.length;
  const prompt = usePrompt();
  const handleSubmit = form.handleSubmit(async (data) => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("orders.claims.confirmText"),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel"),
      variant: "confirmation"
    });
    if (!res) {
      return;
    }
    await confirmClaimRequest(
      { no_notification: !data.send_notification },
      {
        onSuccess: () => {
          toast.success(t("orders.claims.toast.confirmedSuccessfully"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  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 = previewItems.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 = async (selectedLocationId) => {
    if (!preview?.order_change?.return_id) return;
    await updateReturn({ location_id: selectedLocationId ?? null });
  };
  const onShippingOptionChange = async (selectedOptionId) => {
    const inboundShippingMethods = (preview.shipping_methods ?? []).filter(
      (s) => {
        const action = s.actions?.find(
          (a) => a.action === "SHIPPING_ADD" && !!a.return_id
        );
        return action && !!action?.return_id;
      }
    );
    const promises = inboundShippingMethods.filter(Boolean).map((inboundShippingMethod) => {
      const action = inboundShippingMethod.actions?.find(
        (a) => a.action === "SHIPPING_ADD" && !!a.return_id
      );
      if (action) {
        return deleteInboundShipping(action.id);
      }
      return Promise.resolve();
    });
    await Promise.all(promises);
    if (selectedOptionId) {
      await addInboundShipping(
        { shipping_option_id: selectedOptionId },
        {
          onError: (error) => {
            toast.error(error.message);
          }
        }
      );
    }
  };
  useEffect(() => {
    return () => {
      if (IS_CANCELING) {
        cancelClaimRequest(void 0, {
          onSuccess: () => {
            toast.success(t("orders.claims.toast.canceledSuccessfully"));
          },
          onError: (error) => {
            toast.error(error.message);
          }
        });
        IS_CANCELING = false;
      }
    };
  }, []);
  useEffect(() => {
    setInventoryMap({});
  }, [inboundItems.length]);
  const estimatedDifference = (preview.summary?.pending_difference ?? 0) - inboundPreviewItems.reduce(
    (acc, item) => acc + (item.total ?? 0),
    0
  );
  const currencyCode = order.currency_code;
  return /* @__PURE__ */ jsx8(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs5(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsx8(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx8(RouteFocusModal.Body, { className: "flex size-full justify-center overflow-y-auto", children: /* @__PURE__ */ jsxs5("div", { className: "mt-16 w-[720px] max-w-[100%] px-4 md:p-0", children: [
      /* @__PURE__ */ jsx8(Heading2, { level: "h1", children: t("orders.claims.create") }),
      /* @__PURE__ */ jsxs5("div", { className: "mt-8 flex items-center justify-between", children: [
        /* @__PURE__ */ jsx8(Heading2, { level: "h2", children: t("orders.returns.inbound") }),
        /* @__PURE__ */ jsxs5(StackedFocusModal, { id: "inbound-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(
              AddClaimItemsTable,
              {
                items: order.items,
                selectedItems: inboundItems.map((i) => i.item_id),
                currencyCode,
                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__ */ 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"
              )
            ] }) }) })
          ] })
        ] })
      ] }),
      showInboundItemsPlaceholder && /* @__PURE__ */ jsx8(ItemPlaceholder, {}),
      inboundItems.map(
        (item, index) => previewItemsMap.get(item.item_id) && itemsMap.get(item.item_id) && /* @__PURE__ */ jsx8(
          ClaimInboundItem,
          {
            item: itemsMap.get(item.item_id),
            previewItem: previewItemsMap.get(item.item_id),
            currencyCode,
            form,
            onRemove: () => {
              const actionId = previewItems.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 = previewItems.find((i) => i.id === item.item_id)?.actions?.find((a) => a.action === "RETURN_ITEM");
              if (action) {
                updateInboundItem(
                  { ...payload, actionId: action.id },
                  {
                    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__ */ jsxs5("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.returns.location") }),
            /* @__PURE__ */ jsx8(Form.Hint, { className: "!mt-1", children: t("orders.returns.locationHint") })
          ] }),
          /* @__PURE__ */ jsx8(
            Form.Field,
            {
              control: form.control,
              name: "location_id",
              render: ({ field: { value, onChange, ...field } }) => {
                return /* @__PURE__ */ jsx8(Form.Item, { children: /* @__PURE__ */ jsx8(Form.Control, { children: /* @__PURE__ */ jsx8(
                  Combobox,
                  {
                    ...field,
                    value: value ?? void 0,
                    onChange: (v) => {
                      onChange(v);
                      onLocationChange(v);
                    },
                    options: (stockLocations ?? []).map(
                      (stockLocation) => ({
                        label: stockLocation.name,
                        value: stockLocation.id
                      })
                    )
                  }
                ) }) });
              }
            }
          )
        ] }),
        /* @__PURE__ */ jsxs5("div", { className: "grid grid-cols-1 gap-2 md:grid-cols-2", children: [
          /* @__PURE__ */ jsxs5("div", { children: [
            /* @__PURE__ */ jsxs5(Form.Label, { children: [
              t("orders.returns.inboundShipping"),
              /* @__PURE__ */ jsxs5(
                Text4,
                {
                  size: "small",
                  leading: "compact",
                  className: "text-ui-fg-muted ml-1 inline",
                  children: [
                    "(",
                    t("fields.optional"),
                    ")"
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsx8(Form.Hint, { className: "!mt-1", children: t("orders.returns.inboundShippingHint") })
          ] }),
          /* @__PURE__ */ jsx8(
            Form.Field,
            {
              control: form.control,
              name: "inbound_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: inboundShippingOptions.map(
                      (so) => ({
                        label: so.name,
                        value: so.id
                      })
                    ),
                    disabled: !locationId,
                    noResultsPlaceholder: /* @__PURE__ */ jsx8(ReturnShippingPlaceholder, {})
                  }
                ) }) });
              }
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsx8(
        ClaimOutboundSection,
        {
          form,
          currencyCode,
          disabled: isRequestLoading
        }
      ),
      /* @__PURE__ */ jsxs5("div", { className: "mt-8 border-y border-dotted py-4", children: [
        /* @__PURE__ */ jsxs5("div", { className: "mb-2 flex items-center justify-between", children: [
          /* @__PURE__ */ jsx8("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.returns.inboundTotal") }),
          /* @__PURE__ */ jsx8("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(
            inboundPreviewItems.reduce((acc, item) => {
              const action = item.actions?.find(
                (act) => act.action === "RETURN_ITEM"
              );
              return acc + Number(action?.amount || 0);
            }, 0) * -1,
            currencyCode
          ) })
        ] }),
        /* @__PURE__ */ jsxs5("div", { className: "mt-4 flex items-center justify-between border-t border-dotted pt-4", children: [
          /* @__PURE__ */ jsx8("span", { className: "txt-small font-medium", children: t("orders.claims.refundAmount") }),
          /* @__PURE__ */ jsx8("span", { className: "txt-small font-medium", children: getStylizedAmount(estimatedDifference, currencyCode) })
        ] })
      ] }),
      /* @__PURE__ */ jsx8("div", { className: "bg-ui-bg-field mt-8 rounded-lg border py-2 pl-2 pr-4", children: /* @__PURE__ */ jsx8(
        Form.Field,
        {
          control: form.control,
          name: "send_notification",
          render: ({ field: { onChange, value, ...field } }) => {
            return /* @__PURE__ */ jsxs5(Form.Item, { children: [
              /* @__PURE__ */ jsxs5("div", { className: "flex items-center", children: [
                /* @__PURE__ */ jsx8(Form.Control, { className: "mr-4 self-start", children: /* @__PURE__ */ jsx8(
                  Switch,
                  {
                    dir: "ltr",
                    className: "mt-[2px] rtl:rotate-180",
                    checked: !!value,
                    onCheckedChange: onChange,
                    ...field
                  }
                ) }),
                /* @__PURE__ */ jsxs5("div", { className: "block", children: [
                  /* @__PURE__ */ jsx8(Form.Label, { children: t("orders.returns.sendNotification") }),
                  /* @__PURE__ */ jsx8(Form.Hint, { className: "!mt-1", children: t("orders.returns.sendNotificationHint") })
                ] })
              ] }),
              /* @__PURE__ */ jsx8(Form.ErrorMessage, {})
            ] });
          }
        }
      ) }),
      /* @__PURE__ */ jsx8("div", { className: "p-8" })
    ] }) }),
    /* @__PURE__ */ jsx8(RouteFocusModal.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",
          onClick: () => IS_CANCELING = true,
          variant: "secondary",
          size: "small",
          children: t("orders.claims.cancel.title")
        }
      ) }),
      /* @__PURE__ */ jsx8(
        Button2,
        {
          type: "submit",
          variant: "primary",
          size: "small",
          isLoading: isRequestLoading,
          children: t("orders.claims.confirm")
        },
        "submit-button"
      )
    ] }) }) })
  ] }) });
};

// src/pages/orders/[id]/claims/create/index.tsx
import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
var IS_REQUEST_RUNNING = false;
var Component = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation11();
  const { order } = useOrder(id, {
    fields: DEFAULT_FIELDS
  });
  const { order: preview } = useOrderPreview(id);
  const [activeClaimId, setActiveClaimId] = useState4();
  const { mutateAsync: createClaim } = useCreateClaim(order?.id ?? "");
  const { claim } = useClaim(activeClaimId, void 0, {
    enabled: !!activeClaimId
  });
  const { return: orderReturn } = useReturn(claim?.return_id, void 0, {
    enabled: !!claim?.return_id
  });
  useEffect2(() => {
    async function run() {
      if (IS_REQUEST_RUNNING || !preview) {
        return;
      }
      if (preview.order_change) {
        if (preview.order_change.change_type === "claim") {
          setActiveClaimId(preview.order_change.claim_id);
        } else {
          navigate(`/orders/${preview.id}`, { replace: true });
          toast2.error(t("orders.claims.activeChangeError"));
        }
        return;
      }
      IS_REQUEST_RUNNING = true;
      try {
        const { claim: createdClaim } = await createClaim({
          order_id: preview.id,
          type: "replace"
        });
        setActiveClaimId(createdClaim.id);
      } catch (e) {
        toast2.error(
          e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
        );
        navigate(`/orders/${preview.id}`, { replace: true });
      } finally {
        IS_REQUEST_RUNNING = false;
      }
    }
    run();
  }, [preview]);
  return /* @__PURE__ */ jsxs6(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx9(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx9("span", { className: "sr-only", children: t("orders.claims.title") }) }),
    /* @__PURE__ */ jsx9(RouteFocusModal.Description, { className: "sr-only", children: t("orders.claims.title") }),
    claim && preview && order && /* @__PURE__ */ jsx9(
      ClaimCreateForm,
      {
        order,
        claim,
        preview,
        orderReturn
      }
    )
  ] });
};
var create_default = Component;
export {
  Component,
  create_default as default
};
