import {
  useAddOrderEditItems,
  useCancelOrderEdit,
  useCreateOrderEdit,
  useRemoveOrderEditItem,
  useRequestOrderEdit,
  useUpdateOrderEditAddedItem,
  useUpdateOrderEditOriginalItem
} from "./chunk-5VMJCLUP.js";
import {
  MoneyAmountCell
} from "./chunk-2Y3WMGN6.js";
import {
  DEFAULT_FIELDS
} from "./chunk-Y2M536WR.js";
import {
  getStylizedAmount
} from "./chunk-PXYDR7WQ.js";
import {
  ProductCell,
  ProductHeader
} from "./chunk-FWPGOIFA.js";
import "./chunk-PHOCVOZ5.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import "./chunk-YBZWO4ZV.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-3EF54XFY.js";
import "./chunk-IQPN4PZJ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-KBYZLKI4.js";
import "./chunk-YWWUOGJA.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useVariants
} from "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import "./chunk-O4STPJR2.js";
import {
  useOrder,
  useOrderPreview
} from "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/orders/order-create-edit/order-edit-create.tsx
import { toast as toast4 } from "@medusajs/ui";
import { useEffect as useEffect2 } from "react";
import { useTranslation as useTranslation7 } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";

// src/pages/orders/order-create-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/order-create-edit/components/order-edit-create-form/order-edit-items-section.tsx
import { useCallback, useEffect, useMemo as useMemo3, useState as useState2 } from "react";
import { MagnifyingGlass } from "@medusajs/icons";
import { Button, Heading, Input as Input2, Text as Text2, toast as toast2 } from "@medusajs/ui";
import debounce from "lodash/debounce";
import { useTranslation as useTranslation5 } from "react-i18next";

// src/pages/orders/order-create-edit/components/add-order-edit-items-table/add-order-edit-items-table.tsx
import { useState } from "react";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/orders/order-create-edit/components/add-order-edit-items-table/use-order-edit-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 useOrderEditItemsTableColumns = (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 }) => {
          return /* @__PURE__ */ jsx(ProductCell, { product: row.original.product });
        }
      }),
      columnHelper.accessor("sku", {
        header: t("fields.sku"),
        cell: ({ getValue }) => {
          return getValue() || "-";
        }
      }),
      columnHelper.accessor("title", {
        header: t("fields.title")
      })
    ],
    [t, currencyCode]
  );
};

// src/pages/orders/order-create-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/order-create-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/order-create-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 AddOrderEditItemsTable = ({
  onSelectionChange,
  currencyCode
}) => {
  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 { variants = [], count } = useVariants({
    ...searchParams,
    fields: "*inventory_items.inventory.location_levels,+inventory_quantity"
  });
  const columns = useOrderEditItemsTableColumns(currencyCode);
  const filters = useOrderEditItemTableFilters();
  const { table } = useDataTable({
    data: variants,
    columns,
    count,
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enableRowSelection: (_row) => {
      return true;
    },
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col overflow-hidden", children: /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count,
      filters,
      pagination: true,
      layout: "fill",
      search: true,
      orderBy: [
        { key: "product_id", label: t("fields.product") },
        { key: "title", label: t("fields.title") },
        { key: "sku", label: t("fields.sku") }
      ],
      prefix: PREFIX,
      queryObject: raw
    }
  ) });
};

// src/pages/orders/order-create-edit/components/order-edit-create-form/order-edit-item.tsx
import { ArrowUturnLeft, DocumentSeries, XCircle } from "@medusajs/icons";
import { Badge, Input, Text, toast } from "@medusajs/ui";
import { useTranslation as useTranslation4 } from "react-i18next";
import { useMemo as useMemo2 } from "react";
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
function OrderEditItem({ item, currencyCode, orderId }) {
  const { t } = useTranslation4();
  const { mutateAsync: addItems } = useAddOrderEditItems(orderId);
  const { mutateAsync: updateAddedItem } = useUpdateOrderEditAddedItem(orderId);
  const { mutateAsync: updateOriginalItem } = useUpdateOrderEditOriginalItem(orderId);
  const { mutateAsync: undoAction } = useRemoveOrderEditItem(orderId);
  const isAddedItem = useMemo2(
    () => !!item.actions?.find((a) => a.action === "ITEM_ADD"),
    [item]
  );
  const isItemUpdated = useMemo2(
    () => !!item.actions?.find((a) => a.action === "ITEM_UPDATE"),
    [item]
  );
  const isItemRemoved = useMemo2(() => {
    const updateAction = item.actions?.find((a) => a.action === "ITEM_UPDATE");
    return !!updateAction && item.quantity === item.detail.fulfilled_quantity;
  }, [item]);
  const onUpdate = async (quantity) => {
    if (quantity <= item.detail.fulfilled_quantity) {
      toast.error(t("orders.edits.validation.quantityLowerThanFulfillment"));
      return;
    }
    if (quantity === item.quantity) {
      return;
    }
    const addItemAction = item.actions?.find((a) => a.action === "ITEM_ADD");
    try {
      if (addItemAction) {
        await updateAddedItem({ quantity, actionId: addItemAction.id });
      } else {
        await updateOriginalItem({ quantity, itemId: item.id });
      }
    } catch (e) {
      toast.error(e.message);
    }
  };
  const onRemove = async () => {
    const addItemAction = item.actions?.find((a) => a.action === "ITEM_ADD");
    try {
      if (addItemAction) {
        await undoAction(addItemAction.id);
      } else {
        await updateOriginalItem({
          quantity: item.detail.fulfilled_quantity,
          //
          itemId: item.id
        });
      }
    } catch (e) {
      toast.error(e.message);
    }
  };
  const onRemoveUndo = async () => {
    const updateItemAction = item.actions?.find(
      (a) => a.action === "ITEM_UPDATE"
    );
    try {
      if (updateItemAction) {
        await undoAction(updateItemAction.id);
      }
    } catch (e) {
      toast.error(e.message);
    }
  };
  const onDuplicate = async () => {
    if (!item.variant_id) {
      toast.error(t("orders.edits.duplicateItemErrorToast"));
      return;
    }
    try {
      await addItems({
        items: [
          {
            variant_id: item.variant_id,
            quantity: item.quantity
          }
        ]
      });
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "An error occurred");
    }
  };
  return /* @__PURE__ */ jsx3(
    "div",
    {
      className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl ",
      "data-testid": `order-edit-item-${item.id}`,
      children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-x-2 gap-y-2 p-3 text-sm md:flex-row", "data-testid": `order-edit-item-${item.id}-content`, children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center justify-between", "data-testid": `order-edit-item-${item.id}-info`, children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-row items-center gap-x-3", "data-testid": `order-edit-item-${item.id}-details`, children: [
            /* @__PURE__ */ jsx3(Thumbnail, { src: item.thumbnail, "data-testid": `order-edit-item-${item.id}-thumbnail` }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col", "data-testid": `order-edit-item-${item.id}-text`, children: [
              /* @__PURE__ */ jsxs("div", { "data-testid": `order-edit-item-${item.id}-title`, children: [
                /* @__PURE__ */ jsxs(Text, { className: "txt-small", as: "span", weight: "plus", children: [
                  item.title,
                  " "
                ] }),
                item.variant_sku && /* @__PURE__ */ jsxs("span", { "data-testid": `order-edit-item-${item.id}-sku`, children: [
                  "(",
                  item.variant_sku,
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ jsx3(Text, { as: "div", className: "text-ui-fg-subtle txt-small", "data-testid": `order-edit-item-${item.id}-subtitle`, children: item.subtitle })
            ] })
          ] }),
          isAddedItem && /* @__PURE__ */ jsx3(Badge, { size: "2xsmall", rounded: "full", color: "blue", className: "mr-1", "data-testid": `order-edit-item-${item.id}-new-badge`, children: t("general.new") }),
          isItemRemoved ? /* @__PURE__ */ jsx3(Badge, { size: "2xsmall", rounded: "full", color: "red", className: "mr-1", "data-testid": `order-edit-item-${item.id}-removed-badge`, children: t("general.removed") }) : isItemUpdated && /* @__PURE__ */ jsx3(
            Badge,
            {
              size: "2xsmall",
              rounded: "full",
              color: "orange",
              className: "mr-1",
              "data-testid": `order-edit-item-${item.id}-modified-badge`,
              children: t("general.modified")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 justify-between", "data-testid": `order-edit-item-${item.id}-actions`, children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-grow items-center gap-2", "data-testid": `order-edit-item-${item.id}-quantity`, children: [
            /* @__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",
                disabled: item.detail.fulfilled_quantity === item.quantity,
                min: item.detail.fulfilled_quantity,
                defaultValue: item.quantity,
                onBlur: (e) => {
                  const val = e.target.value;
                  const payload = val === "" ? null : Number(val);
                  if (payload) {
                    onUpdate(payload);
                  }
                },
                "data-testid": `order-edit-item-${item.id}-quantity-input`
              }
            ),
            /* @__PURE__ */ jsx3(Text, { className: "txt-small text-ui-fg-subtle", "data-testid": `order-edit-item-${item.id}-quantity-label`, children: t("fields.qty") })
          ] }),
          /* @__PURE__ */ jsx3("div", { className: "text-ui-fg-subtle txt-small mr-2 flex flex-shrink-0", "data-testid": `order-edit-item-${item.id}-total`, children: /* @__PURE__ */ jsx3(MoneyAmountCell, { currencyCode, amount: item.total }) }),
          /* @__PURE__ */ jsx3(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    {
                      label: t("actions.duplicate"),
                      onClick: onDuplicate,
                      icon: /* @__PURE__ */ jsx3(DocumentSeries, {})
                    }
                  ]
                },
                {
                  actions: [
                    !isItemRemoved ? {
                      label: t("actions.remove"),
                      onClick: onRemove,
                      icon: /* @__PURE__ */ jsx3(XCircle, {}),
                      disabled: item.detail.fulfilled_quantity === item.quantity
                    } : {
                      label: t("actions.undo"),
                      onClick: onRemoveUndo,
                      icon: /* @__PURE__ */ jsx3(ArrowUturnLeft, {})
                    }
                  ].filter(Boolean)
                }
              ],
              "data-testid": `order-edit-item-${item.id}-action-menu`
            }
          )
        ] })
      ] })
    },
    item.quantity
  );
}

// src/pages/orders/order-create-edit/components/order-edit-create-form/order-edit-items-section.tsx
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
var addedVariants = [];
var OrderEditItemsSection = ({
  order,
  preview
}) => {
  const { t } = useTranslation5();
  const { setIsOpen } = useStackedModal();
  const [filterTerm, setFilterTerm] = useState2("");
  const { mutateAsync: addItems, isPending } = useAddOrderEditItems(order.id);
  const onItemsSelected = async () => {
    await addItems(
      {
        items: addedVariants.map((i) => ({
          variant_id: i,
          quantity: 1
        }))
      },
      {
        onError: (e) => {
          toast2.error(e.message);
        }
      }
    );
    setIsOpen("inbound-items", false);
  };
  const debouncedOnChange = useCallback(
    debounce((e) => {
      const value = e.target.value;
      setFilterTerm(value);
    }, 500),
    [setFilterTerm]
  );
  useEffect(() => {
    return () => {
      debouncedOnChange.cancel();
    };
  }, [debouncedOnChange]);
  const filteredItems = useMemo3(() => {
    const lowerFilterTerm = filterTerm.toLowerCase();
    return preview.items.filter(
      (i) => i.title.toLowerCase().includes(filterTerm) || i.product_title?.toLowerCase().includes(filterTerm)
    );
  }, [preview, filterTerm]);
  return /* @__PURE__ */ jsxs2("div", { "data-testid": "order-edit-items-section", children: [
    /* @__PURE__ */ jsxs2("div", { className: "mb-3 mt-8 flex items-center justify-between", "data-testid": "order-edit-items-section-header", children: [
      /* @__PURE__ */ jsx4(Heading, { level: "h2", "data-testid": "order-edit-items-section-heading", children: t("fields.items") }),
      /* @__PURE__ */ jsxs2("div", { className: "flex gap-2", "data-testid": "order-edit-items-section-actions", children: [
        /* @__PURE__ */ jsx4(
          Input2,
          {
            onChange: debouncedOnChange,
            placeholder: t("fields.search"),
            autoComplete: "off",
            type: "search",
            "data-testid": "order-edit-items-section-search-input"
          }
        ),
        /* @__PURE__ */ jsxs2(StackedFocusModal, { id: "inbound-items", children: [
          /* @__PURE__ */ jsx4(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx4(Button, { variant: "secondary", size: "small", "data-testid": "order-edit-items-section-add-items-button", children: t("actions.addItems") }) }),
          /* @__PURE__ */ jsxs2(StackedFocusModal.Content, { children: [
            /* @__PURE__ */ jsx4(StackedFocusModal.Header, { "data-testid": "order-edit-items-section-add-items-modal-header" }),
            /* @__PURE__ */ jsx4(
              AddOrderEditItemsTable,
              {
                currencyCode: order.currency_code,
                onSelectionChange: (finalSelection) => {
                  addedVariants = finalSelection;
                }
              }
            ),
            /* @__PURE__ */ jsx4(StackedFocusModal.Footer, { "data-testid": "order-edit-items-section-add-items-modal-footer", children: /* @__PURE__ */ jsx4("div", { className: "flex w-full items-center justify-end gap-x-4", "data-testid": "order-edit-items-section-add-items-modal-footer-actions", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
              /* @__PURE__ */ jsx4(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx4(Button, { type: "button", variant: "secondary", size: "small", "data-testid": "order-edit-items-section-add-items-modal-cancel-button", children: t("actions.cancel") }) }),
              /* @__PURE__ */ jsx4(
                Button,
                {
                  type: "submit",
                  variant: "primary",
                  size: "small",
                  role: "button",
                  disabled: isPending,
                  onClick: async () => await onItemsSelected(),
                  "data-testid": "order-edit-items-section-add-items-modal-save-button",
                  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__ */ jsxs2("div", { className: "flex flex-col items-center justify-center gap-y-2 rounded-xl bg-ui-bg-subtle p-3 text-center shadow-elevation-card-rest", children: [
      /* @__PURE__ */ jsx4(MagnifyingGlass, { className: "text-ui-fg-subtle" }),
      /* @__PURE__ */ jsx4(Text2, { size: "small", leading: "compact", weight: "plus", children: t("general.noSearchResults") })
    ] })
  ] });
};

// src/pages/orders/order-create-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/order-create-edit/components/order-edit-create-form/order-edit-create-form.tsx
import { jsx as jsx5, jsxs as jsxs3 } 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: {
      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();
    } catch (e) {
      toast3.error(t("general.error"), {
        description: e.message
      });
    }
  });
  return /* @__PURE__ */ jsx5(
    RouteFocusModal.Form,
    {
      form,
      onClose: (isSubmitSuccessful) => {
        if (!isSubmitSuccessful) {
          cancelOrderEditRequest(void 0, {
            onSuccess: () => {
              toast3.success(t("orders.edits.cancelSuccessToast"));
            },
            onError: (error) => {
              toast3.error(error.message);
            }
          });
        }
      },
      "data-testid": "order-edit-create-form",
      children: /* @__PURE__ */ jsxs3(
        KeyboundForm,
        {
          onSubmit: handleSubmit,
          className: "flex h-full flex-col",
          "data-testid": "order-create-edit-form",
          children: [
            /* @__PURE__ */ jsx5(RouteFocusModal.Header, { "data-testid": "order-edit-create-header" }),
            /* @__PURE__ */ jsx5(
              RouteFocusModal.Body,
              {
                className: "flex size-full justify-center overflow-y-auto",
                "data-testid": "order-edit-create-body",
                children: /* @__PURE__ */ jsxs3(
                  "div",
                  {
                    className: "mt-16 w-[720px] max-w-[100%] px-4 md:p-0",
                    "data-testid": "order-create-edit-form-content",
                    children: [
                      /* @__PURE__ */ jsx5(
                        Heading2,
                        {
                          level: "h1",
                          "data-testid": "order-edit-create-heading",
                          children: t("orders.edits.create")
                        }
                      ),
                      /* @__PURE__ */ jsx5(
                        OrderEditItemsSection,
                        {
                          preview,
                          order
                        }
                      ),
                      /* @__PURE__ */ jsxs3(
                        "div",
                        {
                          className: "mt-8 border-y border-dotted py-4",
                          "data-testid": "order-edit-create-totals",
                          children: [
                            /* @__PURE__ */ jsxs3(
                              "div",
                              {
                                className: "mb-2 flex items-center justify-between",
                                "data-testid": "order-edit-create-current-total",
                                children: [
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small text-ui-fg-subtle",
                                      "data-testid": "order-create-edit-form-current-total-label",
                                      children: t("orders.edits.currentTotal")
                                    }
                                  ),
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small text-ui-fg-subtle",
                                      "data-testid": "order-create-edit-form-current-total-value",
                                      children: getStylizedAmount(order.total, order.currency_code)
                                    }
                                  )
                                ]
                              }
                            ),
                            /* @__PURE__ */ jsxs3(
                              "div",
                              {
                                className: "mb-2 flex items-center justify-between",
                                "data-testid": "order-edit-create-new-total",
                                children: [
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small text-ui-fg-subtle",
                                      "data-testid": "order-create-edit-form-new-total-label",
                                      children: t("orders.edits.newTotal")
                                    }
                                  ),
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small text-ui-fg-subtle",
                                      "data-testid": "order-create-edit-form-new-total-value",
                                      children: getStylizedAmount(preview.total, order.currency_code)
                                    }
                                  )
                                ]
                              }
                            ),
                            /* @__PURE__ */ jsxs3(
                              "div",
                              {
                                className: "mt-4 flex items-center justify-between border-t border-dotted pt-4",
                                "data-testid": "order-edit-create-refund-amount",
                                children: [
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small font-medium",
                                      "data-testid": "order-create-edit-form-refund-amount-label",
                                      children: t("orders.exchanges.refundAmount")
                                    }
                                  ),
                                  /* @__PURE__ */ jsx5(
                                    "span",
                                    {
                                      className: "txt-small font-medium",
                                      "data-testid": "order-create-edit-form-refund-amount-value",
                                      children: getStylizedAmount(preview.summary.pending_difference, order.currency_code)
                                    }
                                  )
                                ]
                              }
                            )
                          ]
                        }
                      ),
                      /* @__PURE__ */ jsx5(
                        Form.Field,
                        {
                          control: form.control,
                          name: "note",
                          render: ({ field }) => {
                            return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "order-edit-create-note-item", children: [
                              /* @__PURE__ */ jsxs3("div", { className: "mt-8 flex", children: [
                                /* @__PURE__ */ jsxs3("div", { className: "block flex-1", children: [
                                  /* @__PURE__ */ jsx5(Form.Label, { "data-testid": "order-edit-create-note-label", children: t("fields.note") }),
                                  /* @__PURE__ */ jsx5(
                                    Form.Hint,
                                    {
                                      className: "!mt-1",
                                      "data-testid": "order-edit-create-note-hint",
                                      children: t("orders.edits.noteHint")
                                    }
                                  )
                                ] }),
                                /* @__PURE__ */ jsx5("div", { className: "w-full flex-1 flex-grow", children: /* @__PURE__ */ jsx5(Form.Control, { "data-testid": "order-edit-create-note-control", children: /* @__PURE__ */ jsx5(
                                  Input3,
                                  {
                                    ...field,
                                    placeholder: t("fields.note"),
                                    "data-testid": "order-edit-create-note-input"
                                  }
                                ) }) })
                              ] }),
                              /* @__PURE__ */ jsx5(Form.ErrorMessage, { "data-testid": "order-create-edit-form-note-error" })
                            ] });
                          }
                        }
                      ),
                      /* @__PURE__ */ jsx5(
                        "div",
                        {
                          className: "mt-8 rounded-lg border bg-ui-bg-field py-2 pl-2 pr-4",
                          "data-testid": "order-edit-create-notification",
                          children: /* @__PURE__ */ jsx5(
                            Form.Field,
                            {
                              control: form.control,
                              name: "send_notification",
                              render: ({ field: { onChange, value, ...field } }) => {
                                return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "order-edit-create-notification-item", children: [
                                  /* @__PURE__ */ jsxs3(
                                    "div",
                                    {
                                      className: "flex items-center",
                                      "data-testid": "order-create-edit-form-notification-control",
                                      children: [
                                        /* @__PURE__ */ jsx5(
                                          Form.Control,
                                          {
                                            className: "mr-4 self-start",
                                            "data-testid": "order-edit-create-notification-control",
                                            children: /* @__PURE__ */ jsx5(
                                              Switch,
                                              {
                                                dir: "ltr",
                                                className: "mt-[2px] rtl:rotate-180",
                                                checked: !!value,
                                                onCheckedChange: onChange,
                                                ...field,
                                                "data-testid": "order-edit-create-notification-switch"
                                              }
                                            )
                                          }
                                        ),
                                        /* @__PURE__ */ jsxs3("div", { className: "block", children: [
                                          /* @__PURE__ */ jsx5(Form.Label, { "data-testid": "order-edit-create-notification-label", children: t("orders.returns.sendNotification") }),
                                          /* @__PURE__ */ jsx5(
                                            Form.Hint,
                                            {
                                              className: "!mt-1",
                                              "data-testid": "order-edit-create-notification-hint",
                                              children: t("orders.returns.sendNotificationHint")
                                            }
                                          )
                                        ] })
                                      ]
                                    }
                                  ),
                                  /* @__PURE__ */ jsx5(Form.ErrorMessage, { "data-testid": "order-edit-create-notification-error" })
                                ] });
                              }
                            }
                          )
                        }
                      ),
                      /* @__PURE__ */ jsx5("div", { className: "p-8" })
                    ]
                  }
                )
              }
            ),
            /* @__PURE__ */ jsx5(RouteFocusModal.Footer, { "data-testid": "order-edit-create-footer", children: /* @__PURE__ */ jsx5(
              "div",
              {
                className: "flex w-full items-center justify-end gap-x-4",
                "data-testid": "order-create-edit-form-footer-actions",
                children: /* @__PURE__ */ jsxs3("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": "order-edit-create-cancel-button",
                      children: t("orders.edits.cancel")
                    }
                  ) }),
                  /* @__PURE__ */ jsx5(
                    Button2,
                    {
                      type: "submit",
                      variant: "primary",
                      size: "small",
                      isLoading: isRequestRunning,
                      "data-testid": "order-edit-create-confirm-button",
                      children: t("orders.edits.confirm")
                    },
                    "submit-button"
                  )
                ] })
              }
            ) })
          ]
        }
      )
    }
  );
};

// src/pages/orders/order-create-edit/order-edit-create.tsx
import { jsx as jsx6 } from "react/jsx-runtime";
var IS_REQUEST_RUNNING = false;
var OrderEditCreate = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation7();
  const { order } = useOrder(id, {
    fields: DEFAULT_FIELDS
  });
  const { order: preview } = useOrderPreview(id);
  const { mutateAsync: createOrderEdit } = useCreateOrderEdit(order.id);
  useEffect2(() => {
    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.message);
        navigate(`/orders/${preview.id}`, { replace: true });
      } finally {
        IS_REQUEST_RUNNING = false;
      }
    }
    run();
  }, [preview]);
  return /* @__PURE__ */ jsx6(RouteFocusModal, { "data-testid": "order-edit-create-modal", children: preview && order && /* @__PURE__ */ jsx6(OrderEditCreateForm, { order, preview }) });
};
export {
  OrderEditCreate as Component
};
