import {
  useAddOrderEditItems,
  useCancelOrderEdit,
  useCreateOrderEdit,
  useRemoveOrderEditAddedItem,
  useRequestOrderEdit,
  useUpdateOrderEditAddedItem,
  useUpdateOrderEditOriginalItem
} from "./chunk-RPMYKDNA.js";
import {
  MoneyAmountCell
} from "./chunk-5YZ3G5EZ.js";
import {
  getStylizedAmount
} from "./chunk-XCHKUSUU.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import "./chunk-IQPN4PZJ.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 {
  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]/edit/index.tsx
import { toast as toast4 } from "@medusajs/ui";
import { useEffect } from "react";
import { useTranslation as useTranslation7 } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useLinkQuery } from "@mercurjs/dashboard-shared";

// src/pages/orders/[id]/edit/_components/order-edit-create-form/order-edit-create-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button as Button2, Heading as Heading2, Input as Input3, Switch, toast as toast3, usePrompt } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation6 } from "react-i18next";

// src/pages/orders/[id]/edit/_components/order-edit-create-form/order-edit-items-section.tsx
import { Button, Heading, Input as Input2, toast as toast2 } from "@medusajs/ui";
import { useMemo as useMemo4, useState as useState2 } from "react";
import { useTranslation as useTranslation5 } from "react-i18next";

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

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

// src/pages/orders/[id]/edit/_components/add-order-edit-items-table/use-order-edit-item-table-filters.tsx
import { useTranslation as useTranslation2 } from "react-i18next";
var useOrderEditItemTableFilters = () => {
  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]/edit/_components/add-order-edit-items-table/use-order-edit-item-table-query.tsx
var useOrderEditItemTableQuery = ({
  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]/edit/_components/add-order-edit-items-table/add-order-edit-items-table.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 50;
var PREFIX = "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 AddOrderEditItemsTable = ({
  currencyCode,
  onSelectionChange
}) => {
  const { t } = useTranslation3();
  const [rowSelection, setRowSelection] = useState({});
  const updater = (fn) => {
    const newState = typeof fn === "function" ? fn(rowSelection) : fn;
    setRowSelection(newState);
    onSelectionChange(Object.keys(newState));
  };
  const { searchParams, raw } = useOrderEditItemTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const offersResponse = useOffers({
    ...searchParams,
    fields: OFFER_PICKER_FIELDS
  });
  const rawOffersSource = offersResponse.offers;
  const rawOffers = useMemo2(
    () => rawOffersSource ?? [],
    [rawOffersSource]
  );
  const rawCount = offersResponse.count ?? 0;
  const offers = useMemo2(() => {
    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 = useOrderEditItemsTableColumns();
  const filters = useOrderEditItemTableFilters();
  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_SIZE,
    enableRowSelection: () => true,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx2(
    "div",
    {
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "add-offers-picker",
      children: /* @__PURE__ */ jsx2(
        _DataTable,
        {
          table,
          columns,
          pageSize: PAGE_SIZE,
          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: PREFIX,
          queryObject: raw
        }
      )
    }
  );
};

// src/pages/orders/[id]/edit/_components/order-edit-create-form/order-edit-item.tsx
import { ArrowUturnLeft, ReceiptPercent, XCircle } from "@medusajs/icons";
import { Badge, Input, Text as Text2, toast, Tooltip } from "@medusajs/ui";
import { useMemo as useMemo3 } from "react";
import { useTranslation as useTranslation4 } from "react-i18next";
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
function OrderEditItem({ item, currencyCode, orderId }) {
  const { t } = useTranslation4();
  const { mutateAsync: updateAddedItem } = useUpdateOrderEditAddedItem(orderId);
  const { mutateAsync: updateOriginalItem } = useUpdateOrderEditOriginalItem(orderId);
  const { mutateAsync: undoAction } = useRemoveOrderEditAddedItem(orderId);
  const actions = useMemo3(
    () => item.actions ?? [],
    [item.actions]
  );
  const isAddedItem = useMemo3(
    () => !!actions.find((a) => a.action === "ITEM_ADD"),
    [actions]
  );
  const isItemUpdated = useMemo3(
    () => !!actions.find((a) => a.action === "ITEM_UPDATE"),
    [actions]
  );
  const fulfilledQty = item.detail?.fulfilled_quantity ?? 0;
  const returnedQty = item.detail?.returned_quantity ?? 0;
  const floor = fulfilledQty + returnedQty;
  const isItemRemoved = useMemo3(() => {
    const updateAction = actions.find((a) => a.action === "ITEM_UPDATE");
    return !!updateAction && item.quantity === floor;
  }, [actions, item.quantity, floor]);
  const appliedPromoCodes = useMemo3(() => {
    return (item.adjustments || []).map((adjustment) => adjustment.code).filter((c) => !!c);
  }, [item.adjustments]);
  const onUpdate = async (quantity) => {
    if (quantity < floor) {
      toast.error(t("orders.edits.removeBlockedFulfilledOrReturned"));
      return;
    }
    if (quantity === item.quantity) {
      return;
    }
    const addItemAction = actions.find((a) => a.action === "ITEM_ADD");
    try {
      if (addItemAction) {
        await updateAddedItem({ $actionId: addItemAction.id, quantity });
      } else {
        await updateOriginalItem({ $itemId: item.id, quantity });
      }
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      );
    }
  };
  const onRemove = async () => {
    const addItemAction = actions.find((a) => a.action === "ITEM_ADD");
    try {
      if (addItemAction) {
        await undoAction(addItemAction.id);
      } else {
        await updateOriginalItem({
          $itemId: item.id,
          quantity: floor
        });
      }
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      );
    }
  };
  const onRemoveUndo = async () => {
    const updateItemAction = actions.find((a) => a.action === "ITEM_UPDATE");
    try {
      if (updateItemAction) {
        await undoAction(updateItemAction.id);
      }
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      );
    }
  };
  const isAtFloor = item.quantity === floor;
  const qtyInput = /* @__PURE__ */ jsx3(
    Input,
    {
      className: "bg-ui-bg-base txt-small w-[67px] rounded-lg [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
      type: "number",
      step: "any",
      disabled: isAtFloor,
      min: floor,
      defaultValue: item.quantity,
      "data-testid": `edit-item-${item.id}-qty`,
      onBlur: (e) => {
        const val = e.target.value;
        const payload = val === "" ? null : Number(val);
        if (payload !== null) {
          onUpdate(payload);
        }
      }
    }
  );
  return /* @__PURE__ */ jsx3(
    "div",
    {
      className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl",
      "data-testid": `edit-item-${item.id}`,
      children: /* @__PURE__ */ jsxs2("div", { className: "flex flex-col items-center gap-x-2 gap-y-2 p-3 text-sm md:flex-row", children: [
        /* @__PURE__ */ jsxs2("div", { className: "flex flex-1 items-center justify-between", children: [
          /* @__PURE__ */ jsxs2("div", { className: "flex flex-row items-center gap-x-3", children: [
            /* @__PURE__ */ jsx3(Thumbnail, { src: item.thumbnail }),
            /* @__PURE__ */ jsxs2("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsxs2("div", { children: [
                /* @__PURE__ */ jsxs2(Text2, { className: "txt-small", as: "span", weight: "plus", children: [
                  item.title,
                  " "
                ] }),
                item.variant_sku && /* @__PURE__ */ jsxs2("span", { children: [
                  "(",
                  item.variant_sku,
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ jsx3(Text2, { as: "div", className: "text-ui-fg-subtle txt-small", children: item.subtitle })
            ] })
          ] }),
          isAddedItem && /* @__PURE__ */ jsx3(Badge, { size: "2xsmall", rounded: "full", color: "blue", className: "mr-1", children: t("general.new") }),
          isItemRemoved ? /* @__PURE__ */ jsx3(Badge, { size: "2xsmall", rounded: "full", color: "red", className: "mr-1", children: t("general.removed") }) : isItemUpdated && /* @__PURE__ */ jsx3(
            Badge,
            {
              size: "2xsmall",
              rounded: "full",
              color: "orange",
              className: "mr-1",
              children: t("general.modified")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs2("div", { className: "flex flex-1 items-center justify-between", children: [
          /* @__PURE__ */ jsxs2("div", { className: "flex flex-grow items-center gap-2", children: [
            floor > 0 && isAtFloor ? /* @__PURE__ */ jsx3(
              Tooltip,
              {
                content: t("orders.edits.removeBlockedFulfilledOrReturned"),
                children: qtyInput
              }
            ) : qtyInput,
            /* @__PURE__ */ jsx3(Text2, { className: "txt-small text-ui-fg-subtle", children: t("fields.qty") }),
            appliedPromoCodes.length > 0 && /* @__PURE__ */ jsx3("div", { className: "flex flex-shrink pt-[2px]", children: /* @__PURE__ */ jsx3(
              Tooltip,
              {
                content: /* @__PURE__ */ jsx3("span", { className: "text-pretty", children: appliedPromoCodes.map((code) => /* @__PURE__ */ jsx3("div", { children: code }, code)) }),
                children: /* @__PURE__ */ jsx3(ReceiptPercent, { className: "text-ui-fg-subtle font-normal" })
              }
            ) })
          ] }),
          /* @__PURE__ */ jsx3("div", { className: "text-ui-fg-subtle txt-small mr-2 flex flex-shrink-0", children: /* @__PURE__ */ jsx3(
            MoneyAmountCell,
            {
              currencyCode,
              amount: item.total ?? 0
            }
          ) }),
          /* @__PURE__ */ jsx3(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    !isItemRemoved ? {
                      label: t("actions.remove"),
                      onClick: onRemove,
                      icon: /* @__PURE__ */ jsx3(XCircle, {}),
                      disabled: isAtFloor
                    } : {
                      label: t("actions.undo"),
                      onClick: onRemoveUndo,
                      icon: /* @__PURE__ */ jsx3(ArrowUturnLeft, {})
                    }
                  ]
                }
              ]
            }
          )
        ] })
      ] })
    },
    item.quantity
  );
}

// src/pages/orders/[id]/edit/_components/order-edit-create-form/order-edit-items-section.tsx
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
var addedOffers = [];
var OrderEditItemsSection = ({
  order,
  preview
}) => {
  const { t } = useTranslation5();
  const { setIsOpen } = useStackedModal();
  const [filterTerm, setFilterTerm] = useState2("");
  const { mutateAsync: addItems, isPending } = useAddOrderEditItems(order.id);
  const onItemsSelected = async () => {
    if (!addedOffers.length) {
      setIsOpen("order-edit-add-items", false);
      return;
    }
    try {
      await addItems({
        // Vendor route resolves `offer_id` → variant_id + unit_price
        // server-side. Picker rows are keyed by offer id, not variant id.
        items: addedOffers.map((offer_id) => ({
          offer_id,
          quantity: 1
        }))
      });
      addedOffers = [];
      setIsOpen("order-edit-add-items", false);
    } catch (e) {
      toast2.error(
        e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      );
    }
  };
  const filteredItems = useMemo4(() => {
    const term = filterTerm.toLowerCase();
    if (!term) {
      return preview.items;
    }
    return preview.items.filter(
      (i) => i.title?.toLowerCase().includes(term) || i.product_title?.toLowerCase().includes(term)
    );
  }, [preview, filterTerm]);
  return /* @__PURE__ */ jsxs3("div", { children: [
    /* @__PURE__ */ jsxs3("div", { className: "mb-3 mt-8 flex items-center justify-between", children: [
      /* @__PURE__ */ jsx4(Heading, { level: "h2", children: t("fields.items") }),
      /* @__PURE__ */ jsxs3("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx4(
          Input2,
          {
            value: filterTerm,
            onChange: (e) => setFilterTerm(e.target.value),
            placeholder: t("fields.search"),
            autoComplete: "off",
            type: "search",
            "data-testid": "edit-items-search"
          }
        ),
        /* @__PURE__ */ jsxs3(StackedFocusModal, { id: "order-edit-add-items", children: [
          /* @__PURE__ */ jsx4(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx4(
            Button,
            {
              variant: "secondary",
              size: "small",
              "data-testid": "edit-add-items-trigger",
              children: t("actions.addItems")
            }
          ) }),
          /* @__PURE__ */ jsxs3(StackedFocusModal.Content, { children: [
            /* @__PURE__ */ jsx4(StackedFocusModal.Header, {}),
            /* @__PURE__ */ jsx4(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("orders.edits.addItems") }) }),
            /* @__PURE__ */ jsx4(StackedFocusModal.Description, { className: "sr-only", children: t("orders.edits.addItemsDescription") }),
            /* @__PURE__ */ jsx4(StackedFocusModal.Body, { className: "size-full overflow-hidden", children: /* @__PURE__ */ jsx4(
              AddOrderEditItemsTable,
              {
                currencyCode: order.currency_code,
                onSelectionChange: (finalSelection) => {
                  addedOffers = finalSelection;
                }
              }
            ) }),
            /* @__PURE__ */ jsx4(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsx4("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-end gap-x-2", children: [
              /* @__PURE__ */ jsx4(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx4(
                Button,
                {
                  type: "button",
                  variant: "secondary",
                  size: "small",
                  "data-testid": "edit-add-items-cancel",
                  children: t("actions.cancel")
                }
              ) }),
              /* @__PURE__ */ jsx4(
                Button,
                {
                  type: "submit",
                  variant: "primary",
                  size: "small",
                  disabled: isPending,
                  onClick: async () => await onItemsSelected(),
                  "data-testid": "edit-add-items-save",
                  children: t("actions.save")
                },
                "submit-button"
              )
            ] }) }) })
          ] })
        ] })
      ] })
    ] }),
    filteredItems.map((item) => /* @__PURE__ */ jsx4(
      OrderEditItem,
      {
        item,
        orderId: order.id,
        currencyCode: order.currency_code
      },
      item.id
    )),
    filterTerm && !filteredItems.length && /* @__PURE__ */ jsx4(
      "div",
      {
        style: {
          background: "repeating-linear-gradient(-45deg, rgb(212, 212, 216, 0.15), rgb(212, 212, 216,.15) 10px, transparent 10px, transparent 20px)"
        },
        className: "bg-ui-bg-field mt-4 block h-[56px] w-full rounded-lg border border-dashed"
      }
    )
  ] });
};

// src/pages/orders/[id]/edit/_components/order-edit-create-form/schema.ts
import { z } from "zod";
var OrderEditCreateSchema = z.object({
  note: z.string().optional(),
  send_notification: z.boolean().optional()
});

// src/pages/orders/[id]/edit/_components/order-edit-create-form/order-edit-create-form.tsx
import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
var OrderEditCreateForm = ({
  order,
  preview
}) => {
  const { t } = useTranslation6();
  const { handleSuccess } = useRouteModal();
  const { mutateAsync: cancelOrderEditRequest, isPending: isCanceling } = useCancelOrderEdit(order.id);
  const { mutateAsync: requestOrderEdit, isPending: isRequesting } = useRequestOrderEdit(order.id);
  const isRequestRunning = isCanceling || isRequesting;
  const form = useForm({
    defaultValues: () => {
      return Promise.resolve({
        note: "",
        send_notification: false
      });
    },
    resolver: zodResolver(OrderEditCreateSchema)
  });
  const prompt = usePrompt();
  const handleSubmit = form.handleSubmit(async () => {
    try {
      const res = await prompt({
        title: t("general.areYouSure"),
        description: t("orders.edits.confirmText"),
        confirmText: t("actions.continue"),
        cancelText: t("actions.cancel"),
        variant: "confirmation"
      });
      if (!res) {
        return;
      }
      await requestOrderEdit();
      toast3.success(t("orders.edits.createSuccessToast"));
      handleSuccess(`/orders/${order.id}`);
    } catch (e) {
      toast3.error(t("general.error"), {
        description: e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
      });
    }
  });
  return /* @__PURE__ */ jsx5(
    RouteFocusModal.Form,
    {
      form,
      onClose: (isSubmitSuccessful) => {
        if (!isSubmitSuccessful) {
          cancelOrderEditRequest(void 0, {
            onSuccess: () => {
              toast3.success(t("orders.edits.toast.canceledSuccessfully"));
            },
            onError: (error) => {
              toast3.error(error.message);
            }
          });
        }
      },
      children: /* @__PURE__ */ jsxs4(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
        /* @__PURE__ */ jsx5(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx5(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx5("span", { className: "sr-only", children: t("orders.edits.title") }) }),
        /* @__PURE__ */ jsx5(RouteFocusModal.Description, { className: "sr-only", children: t("orders.edits.title") }),
        /* @__PURE__ */ jsx5(RouteFocusModal.Body, { className: "flex size-full justify-center overflow-y-auto", children: /* @__PURE__ */ jsxs4("div", { className: "mt-16 w-[720px] max-w-[100%] px-4 md:p-0", children: [
          /* @__PURE__ */ jsx5(Heading2, { level: "h1", children: t("orders.edits.create") }),
          /* @__PURE__ */ jsx5(OrderEditItemsSection, { preview, order }),
          /* @__PURE__ */ jsxs4("div", { className: "mt-8 border-y border-dotted py-4", children: [
            /* @__PURE__ */ jsxs4("div", { className: "mb-2 flex items-center justify-between", children: [
              /* @__PURE__ */ jsx5("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.edits.currentTotal") }),
              /* @__PURE__ */ jsx5("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(order.total, order.currency_code) })
            ] }),
            /* @__PURE__ */ jsxs4("div", { className: "mb-2 flex items-center justify-between", children: [
              /* @__PURE__ */ jsx5("span", { className: "txt-small text-ui-fg-subtle", children: t("orders.edits.newTotal") }),
              /* @__PURE__ */ jsx5("span", { className: "txt-small text-ui-fg-subtle", children: getStylizedAmount(preview.total, order.currency_code) })
            ] }),
            /* @__PURE__ */ jsxs4("div", { className: "mt-4 flex items-center justify-between border-t border-dotted pt-4", children: [
              /* @__PURE__ */ jsx5("span", { className: "txt-small font-medium", children: t("orders.edits.differenceDue") }),
              /* @__PURE__ */ jsx5("span", { className: "txt-small font-medium", children: getStylizedAmount(
                preview.summary.pending_difference,
                order.currency_code
              ) })
            ] })
          ] }),
          /* @__PURE__ */ jsx5(
            Form.Field,
            {
              control: form.control,
              name: "note",
              render: ({ field }) => {
                return /* @__PURE__ */ jsx5(Form.Item, { children: /* @__PURE__ */ jsxs4("div", { className: "mt-8 flex", children: [
                  /* @__PURE__ */ jsxs4("div", { className: "block flex-1", children: [
                    /* @__PURE__ */ jsx5(Form.Label, { optional: true, children: t("fields.note") }),
                    /* @__PURE__ */ jsx5(Form.Hint, { className: "!mt-1", children: t("orders.edits.noteHint") })
                  ] }),
                  /* @__PURE__ */ jsx5("div", { className: "w-full flex-1 flex-grow", children: /* @__PURE__ */ jsx5(Form.Control, { children: /* @__PURE__ */ jsx5(Input3, { ...field, "data-testid": "edit-internal-note" }) }) })
                ] }) });
              }
            }
          ),
          /* @__PURE__ */ jsx5("div", { className: "bg-ui-bg-field mt-8 rounded-lg border py-2 pl-2 pr-4", children: /* @__PURE__ */ jsx5(
            Form.Field,
            {
              control: form.control,
              name: "send_notification",
              render: ({ field: { onChange, value, ...field } }) => {
                return /* @__PURE__ */ jsxs4(Form.Item, { children: [
                  /* @__PURE__ */ jsxs4("div", { className: "flex items-center", children: [
                    /* @__PURE__ */ jsx5(Form.Control, { className: "mr-4 self-start", children: /* @__PURE__ */ jsx5(
                      Switch,
                      {
                        dir: "ltr",
                        className: "mt-[2px] rtl:rotate-180",
                        checked: !!value,
                        onCheckedChange: onChange,
                        ...field
                      }
                    ) }),
                    /* @__PURE__ */ jsxs4("div", { className: "block", children: [
                      /* @__PURE__ */ jsx5(Form.Label, { children: t("orders.edits.sendNotification") }),
                      /* @__PURE__ */ jsx5(Form.Hint, { className: "!mt-1", children: t("orders.edits.sendNotificationHint") })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx5(Form.ErrorMessage, {})
                ] });
              }
            }
          ) }),
          /* @__PURE__ */ jsx5("div", { className: "p-8" })
        ] }) }),
        /* @__PURE__ */ jsx5(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsx5("div", { className: "flex w-full items-center justify-end gap-x-4", children: /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx5(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx5(
            Button2,
            {
              type: "button",
              variant: "secondary",
              size: "small",
              "data-testid": "edit-cancel",
              children: t("orders.edits.cancel")
            }
          ) }),
          /* @__PURE__ */ jsx5(
            Button2,
            {
              type: "submit",
              variant: "primary",
              size: "small",
              isLoading: isRequestRunning,
              "data-testid": "edit-confirm",
              children: t("orders.edits.confirm")
            },
            "submit-button"
          )
        ] }) }) })
      ] })
    }
  );
};

// src/pages/orders/[id]/edit/index.tsx
import { jsx as jsx6 } from "react/jsx-runtime";
var IS_REQUEST_RUNNING = false;
var Component = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation7();
  const orderId = id ?? "";
  const query = useLinkQuery(
    "order",
    "currency_code,total,items.*,items.variant.*"
  );
  const { order } = useOrder(orderId, query);
  const { order: preview } = useOrderPreview(orderId);
  const { mutateAsync: createOrderEdit } = useCreateOrderEdit(orderId);
  useEffect(() => {
    async function run() {
      if (IS_REQUEST_RUNNING || !preview) {
        return;
      }
      if (preview.order_change) {
        if (preview.order_change.change_type !== "edit") {
          navigate(`/orders/${preview.id}`, { replace: true });
          toast4.error(t("orders.edits.activeChangeError"));
        }
        return;
      }
      IS_REQUEST_RUNNING = true;
      try {
        await createOrderEdit({
          order_id: preview.id
        });
      } catch (e) {
        toast4.error(
          e instanceof Error ? e.message : t("errorBoundary.defaultTitle")
        );
        navigate(`/orders/${preview.id}`, { replace: true });
      } finally {
        IS_REQUEST_RUNNING = false;
      }
    }
    run();
  }, [preview, createOrderEdit, navigate, t]);
  return /* @__PURE__ */ jsx6(RouteFocusModal, { children: preview && order && /* @__PURE__ */ jsx6(OrderEditCreateForm, { order, preview }) });
};
var edit_default = Component;
export {
  Component,
  edit_default as default
};
