import {
  getFulfillableQuantity
} from "./chunk-RXM4B6HR.js";
import {
  getReservationsLimitCount
} from "./chunk-EEBJYXWA.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import {
  useStockLocations
} from "./chunk-O72AIZUN.js";
import {
  ordersQueryKeys,
  useCreateReservationItem,
  useOrder,
  useReservationItems
} from "./chunk-DIAWPVYS.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/orders/[id]/allocate-items/index.tsx
import { useParams } from "react-router-dom";

// src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useMemo as useMemo2, useState as useState2 } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { Alert, Button, Heading, Input as Input2, Select, toast } from "@medusajs/ui";
import { useForm, useWatch as useWatch2 } from "react-hook-form";

// src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/constants.ts
import { z } from "zod";
var AllocateItemsSchema = z.object({
  location_id: z.string(),
  quantity: z.record(z.string(), z.number().or(z.string())),
  // Keyed by line item id. Defaults to selected; deselected items are
  // excluded from the allocation payload.
  selected: z.record(z.string(), z.boolean())
});

// src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-item.tsx
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Component,
  ExclamationCircleSolid,
  TriangleDownMini
} from "@medusajs/icons";
import { useWatch } from "react-hook-form";
import { Checkbox, Input, Text, clx } from "@medusajs/ui";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var resolveInventoryItemId = (link) => link.inventory_item?.id ?? link.inventory_item_id ?? null;
function OrderAllocateItemsItem({
  item,
  form,
  locationId,
  onQuantityChange,
  onToggleSelected
}) {
  const { t } = useTranslation();
  const inventoryLinks = item.offer?.inventory_item_link ?? [];
  const [isOpen, setIsOpen] = useState(false);
  const quantityField = useWatch({
    control: form.control,
    name: "quantity"
  });
  const isSelected = useWatch({
    control: form.control,
    name: `selected.${item.id}`
  }) !== false;
  const hasInventoryKit = inventoryLinks.length > 1;
  const firstLink = inventoryLinks[0];
  const firstLinkId = firstLink ? resolveInventoryItemId(firstLink) : null;
  const { availableQuantity, inStockQuantity } = useMemo(() => {
    if (!firstLink || !locationId) {
      return {};
    }
    const locationInventory = firstLink.inventory_item?.location_levels?.find(
      (inv) => inv.location_id === locationId
    );
    if (!locationInventory) {
      return {};
    }
    return {
      availableQuantity: locationInventory.available_quantity,
      inStockQuantity: locationInventory.stocked_quantity
    };
  }, [firstLink, locationId]);
  const hasQuantityError = !hasInventoryKit && availableQuantity && firstLinkId && quantityField[`${item.id}-${firstLinkId}`] && Number(quantityField[`${item.id}-${firstLinkId}`]) > availableQuantity;
  const minValue = 0;
  const maxValue = Math.min(
    getFulfillableQuantity(item) ?? 0,
    availableQuantity || Number.MAX_SAFE_INTEGER
  );
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: clx(
        "bg-ui-bg-subtle shadow-elevation-card-rest min-w-[720px] divide-y divide-dashed rounded-xl",
        !isSelected && "opacity-60"
      ),
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3 p-3 text-sm", children: [
          /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              onCheckedChange: (value) => onToggleSelected(item.id, value === true),
              "data-testid": `allocate-item-${item.id}-checkbox`
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
            hasQuantityError && /* @__PURE__ */ jsx(ExclamationCircleSolid, { className: "text-ui-fg-error" }),
            /* @__PURE__ */ jsx(Thumbnail, { src: item.thumbnail }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-row items-center gap-x-1", children: [
                /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", as: "span", children: item.product_title }),
                (item.offer?.sku ?? item.variant_sku) && /* @__PURE__ */ jsxs(
                  Text,
                  {
                    size: "small",
                    weight: "plus",
                    as: "span",
                    className: "text-ui-fg-subtle",
                    children: [
                      "(",
                      item.offer?.sku ?? item.variant_sku,
                      ")"
                    ]
                  }
                ),
                hasInventoryKit && /* @__PURE__ */ jsx(Component, { className: "text-ui-fg-muted ml-1 overflow-visible" })
              ] }),
              /* @__PURE__ */ jsx(Text, { as: "div", className: "text-ui-fg-subtle txt-small", children: item.title })
            ] })
          ] }) }),
          /* @__PURE__ */ jsxs(
            "div",
            {
              className: clx(
                "flex flex-1 items-center gap-x-3",
                hasInventoryKit ? "justify-end" : "justify-between"
              ),
              children: [
                !hasInventoryKit && /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                    /* @__PURE__ */ jsxs("div", { className: "txt-small flex flex-col", children: [
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", children: t("labels.available") }),
                      /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-muted", children: [
                        availableQuantity || "-",
                        availableQuantity && !hasInventoryKit && firstLinkId && quantityField[`${item.id}-${firstLinkId}`] && /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-error txt-small ml-1", children: [
                          "-",
                          quantityField[`${item.id}-${firstLinkId}`]
                        ] })
                      ] })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                    /* @__PURE__ */ jsxs("div", { className: "txt-small flex flex-col", children: [
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", children: t("labels.inStock") }),
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: inStockQuantity || "-" })
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                  /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle txt-small mr-2 flex flex-row items-center gap-2", children: [
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: hasInventoryKit && firstLinkId ? `quantity.${item.id}-` : `quantity.${item.id}-${firstLinkId ?? ""}`,
                        rules: {
                          required: !hasInventoryKit,
                          min: !hasInventoryKit ? minValue : void 0,
                          max: maxValue > 0 ? maxValue : void 0
                        },
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsx(Form.Item, { children: /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              className: "bg-ui-bg-base txt-small w-[46px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
                              type: "number",
                              ...field,
                              disabled: !locationId || !isSelected,
                              onChange: (e) => {
                                const val = e.target.value === "" ? null : Number(e.target.value);
                                if (firstLink) {
                                  onQuantityChange(
                                    firstLink,
                                    item,
                                    hasInventoryKit,
                                    val,
                                    true
                                  );
                                }
                              }
                            }
                          ) }) });
                        }
                      }
                    ),
                    " ",
                    "/ ",
                    item.quantity,
                    " ",
                    t("fields.qty")
                  ] })
                ] })
              ]
            }
          )
        ] }),
        hasInventoryKit && /* @__PURE__ */ jsx("div", { className: "px-4 py-2", children: /* @__PURE__ */ jsxs(
          "div",
          {
            onClick: () => setIsOpen((o) => !o),
            className: "flex items-center gap-x-2",
            children: [
              /* @__PURE__ */ jsx(
                TriangleDownMini,
                {
                  style: { transform: `rotate(${isOpen ? -90 : 0}deg)` },
                  className: "text-ui-fg-muted -mt-[1px]"
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "txt-small text-ui-fg-muted cursor-pointer", children: t("orders.allocateItems.consistsOf", {
                num: inventoryLinks.length
              }) })
            ]
          }
        ) }),
        isOpen && inventoryLinks.map((link, ind) => {
          const inventoryItemId = resolveInventoryItemId(link);
          const location = link.inventory_item?.location_levels?.find(
            (l) => l.location_id === locationId
          );
          const required = link.required_quantity ?? 1;
          const quantityKey = `${item.id}-${inventoryItemId ?? ""}`;
          const childHasError = !!quantityField[quantityKey] && location && Number(quantityField[quantityKey]) > (location.available_quantity ?? 0);
          return /* @__PURE__ */ jsxs(
            "div",
            {
              className: "txt-small flex items-center gap-x-3 p-4",
              children: [
                /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-row items-center gap-3", children: [
                  childHasError && /* @__PURE__ */ jsx(ExclamationCircleSolid, { className: "text-ui-fg-error" }),
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                    /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle", children: link.inventory_item?.title ?? link.inventory_item?.sku ?? `Inventory Item ${ind + 1}` }),
                    /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: t("orders.allocateItems.requires", {
                      num: required
                    }) })
                  ] })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-row justify-between", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                    /* @__PURE__ */ jsxs("div", { className: "txt-small flex flex-col", children: [
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", children: t("labels.available") }),
                      /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-muted", children: [
                        location?.available_quantity || "-",
                        location?.available_quantity && quantityField[quantityKey] && /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-error txt-small ml-1", children: [
                          "-",
                          quantityField[quantityKey]
                        ] })
                      ] })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                    /* @__PURE__ */ jsxs("div", { className: "txt-small flex flex-col", children: [
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", children: t("labels.inStock") }),
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: location?.stocked_quantity || "-" })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-border-strong block h-[12px] w-[1px]" }),
                    /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle txt-small mr-1 flex flex-row items-center gap-2", children: [
                      /* @__PURE__ */ jsx(
                        Form.Field,
                        {
                          control: form.control,
                          name: `quantity.${item.id}-${inventoryItemId ?? ""}`,
                          rules: {
                            required: true,
                            min: 0,
                            max: location?.available_quantity ?? void 0
                          },
                          render: ({ field }) => {
                            return /* @__PURE__ */ jsx(Form.Item, { children: /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                              Input,
                              {
                                className: "bg-ui-bg-base txt-small w-[46px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
                                type: "number",
                                ...field,
                                disabled: !locationId || !isSelected,
                                onChange: (e) => {
                                  const val = e.target.value === "" ? null : Number(e.target.value);
                                  onQuantityChange(
                                    link,
                                    item,
                                    hasInventoryKit,
                                    val
                                  );
                                }
                              }
                            ) }) });
                          }
                        }
                      ),
                      "/ ",
                      item.quantity * required,
                      " ",
                      t("fields.qty")
                    ] })
                  ] })
                ] })
              ]
            },
            link.id ?? inventoryItemId ?? `link-${ind}`
          );
        })
      ]
    }
  );
}

// src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/utils.ts
function getAllocatableItems(items, reservations) {
  const reserved = new Set(
    reservations.map((r) => r.line_item_id).filter((id) => !!id)
  );
  return items.filter(
    (item) => !!item.offer?.inventory_item_link?.length && item.quantity - (item.detail?.fulfilled_quantity ?? 0) > 0 && !reserved.has(item.id)
  );
}
function buildAllocationPayload(quantity, selected) {
  const rows = Object.entries(quantity).filter(([key]) => !key.endsWith("-")).map(([key, value]) => {
    const separatorIndex = key.indexOf("-");
    return {
      lineItemId: key.slice(0, separatorIndex),
      inventoryItemId: key.slice(separatorIndex + 1),
      value
    };
  }).filter((row) => selected[row.lineItemId] !== false);
  if (rows.length === 0) {
    return { ok: false, reason: "no-items" };
  }
  const items = [];
  for (const row of rows) {
    if (row.value === "" || row.value === null || row.value === void 0) {
      return { ok: false, reason: "invalid-quantity" };
    }
    const quantityNumber = Number(row.value);
    if (!Number.isFinite(quantityNumber) || quantityNumber <= 0) {
      return { ok: false, reason: "invalid-quantity" };
    }
    items.push({
      line_item_id: row.lineItemId,
      inventory_item_id: row.inventoryItemId,
      quantity: quantityNumber
    });
  }
  return { ok: true, items };
}

// src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-form.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
function OrderAllocateItemsForm({ order }) {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const [disableSubmit, setDisableSubmit] = useState2(false);
  const [filterTerm, setFilterTerm] = useState2("");
  const { mutateAsync: allocateItems, isPending: isMutating } = useCreateReservationItem();
  const { reservations } = useReservationItems(
    {
      line_item_id: order?.items?.map((i) => i.id),
      limit: getReservationsLimitCount(order)
    },
    { enabled: Array.isArray(order?.items) }
  );
  const itemsToAllocate = useMemo2(
    () => getAllocatableItems(
      order.items,
      reservations ?? []
    ),
    [order.items, reservations]
  );
  const filteredItems = useMemo2(() => {
    return itemsToAllocate.filter(
      (i) => i.variant_title?.toLowerCase().includes(filterTerm) || i.product_title?.toLowerCase().includes(filterTerm)
    );
  }, [itemsToAllocate, filterTerm]);
  const form = useForm({
    defaultValues: {
      location_id: "",
      quantity: defaultAllocations(itemsToAllocate),
      selected: defaultSelected(itemsToAllocate)
    },
    resolver: zodResolver(AllocateItemsSchema)
  });
  const { stock_locations = [] } = useStockLocations();
  const handleSubmit = form.handleSubmit(async (data) => {
    try {
      const result = buildAllocationPayload(data.quantity, data.selected);
      if (!result.ok) {
        form.setError("root.quantityNotAllocated", {
          type: "manual",
          message: result.reason === "no-items" ? t("orders.allocateItems.error.noItemsSelected") : t("orders.allocateItems.error.quantityNotAllocated")
        });
        return;
      }
      const allocatableIds = new Set(itemsToAllocate.map((i) => i.id));
      const allocations = result.items.filter(
        (item) => allocatableIds.has(item.line_item_id)
      );
      if (allocations.length === 0) {
        form.setError("root.quantityNotAllocated", {
          type: "manual",
          message: t("orders.allocateItems.error.noItemsSelected")
        });
        return;
      }
      const promises = allocations.map(
        (item) => allocateItems({
          location_id: data.location_id,
          inventory_item_id: item.inventory_item_id,
          line_item_id: item.line_item_id,
          quantity: item.quantity
        })
      );
      await Promise.all(promises);
      await queryClient.invalidateQueries({
        queryKey: ordersQueryKeys.details()
      });
      handleSuccess(`/orders/${order.id}`);
      toast.success(t("general.success"), {
        description: t("orders.allocateItems.toast.created")
      });
    } catch (e) {
      toast.error(t("general.error"), {
        description: e instanceof Error ? e.message : t("general.unknownError")
      });
    }
  });
  const onToggleSelected = (itemId, checked) => {
    form.setValue(`selected.${itemId}`, checked);
    form.clearErrors("root.quantityNotAllocated");
  };
  const onQuantityChange = (link, lineItem, hasInventoryKit, value, isRoot) => {
    let shouldDisableSubmit = false;
    const inventoryItemId = resolveInventoryItemId2(link);
    const key = isRoot && hasInventoryKit ? `quantity.${lineItem.id}-` : `quantity.${lineItem.id}-${inventoryItemId ?? ""}`;
    form.setValue(key, value ?? "");
    const levels = link.inventory_item?.location_levels;
    if (value && levels) {
      const location = levels.find((l) => l.location_id === selectedLocationId);
      if (location && (location.available_quantity ?? 0) < value) {
        shouldDisableSubmit = true;
      }
    }
    if (hasInventoryKit && !isRoot) {
      form.resetField(`quantity.${lineItem.id}-`, { defaultValue: "" });
    }
    if (hasInventoryKit && isRoot) {
      const item = itemsToAllocate.find((i) => i.id === lineItem.id);
      if (!item || !item.offer?.inventory_item_link) return;
      item.offer.inventory_item_link.forEach((childLink) => {
        const num = value || 0;
        const childInventoryItemId = resolveInventoryItemId2(childLink);
        if (!childInventoryItemId) return;
        const required = childLink.required_quantity ?? 1;
        form.setValue(
          `quantity.${lineItem.id}-${childInventoryItemId}`,
          num * required
        );
        const childLevels = childLink.inventory_item?.location_levels;
        if (value && childLevels) {
          const location = childLevels.find(
            (l) => l.location_id === selectedLocationId
          );
          if (location && (location.available_quantity ?? 0) < num * required) {
            shouldDisableSubmit = true;
          }
        }
      });
    }
    form.clearErrors("root.quantityNotAllocated");
    setDisableSubmit(shouldDisableSubmit);
  };
  const selectedLocationId = useWatch2({
    name: "location_id",
    control: form.control
  });
  useEffect(() => {
    if (selectedLocationId) {
      form.setValue(
        "quantity",
        defaultAllocations(itemsToAllocate, selectedLocationId)
      );
    }
  }, [
    selectedLocationId,
    form,
    itemsToAllocate
  ]);
  const allocationError = form.formState.errors?.root?.quantityNotAllocated?.message;
  return /* @__PURE__ */ jsx2(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs2(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx2(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx2(RouteFocusModal.Body, { className: "flex h-full w-full flex-col items-center divide-y overflow-y-auto", children: /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col items-center overflow-auto p-16", children: /* @__PURE__ */ jsx2("div", { className: "flex w-full max-w-[736px] flex-col justify-center px-2 pb-2", children: /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-8 divide-y divide-dashed", children: [
          /* @__PURE__ */ jsx2(Heading, { children: t("orders.allocateItems.title") }),
          /* @__PURE__ */ jsxs2("div", { className: "flex-1 divide-y divide-dashed pt-8", children: [
            /* @__PURE__ */ jsx2(
              Form.Field,
              {
                control: form.control,
                name: "location_id",
                render: ({ field: { onChange, ref, ...field } }) => {
                  return /* @__PURE__ */ jsxs2(Form.Item, { children: [
                    /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-3", children: [
                      /* @__PURE__ */ jsxs2("div", { className: "flex-1", children: [
                        /* @__PURE__ */ jsx2(Form.Label, { children: t("fields.location") }),
                        /* @__PURE__ */ jsx2(Form.Hint, { children: t("orders.allocateItems.locationDescription") })
                      ] }),
                      /* @__PURE__ */ jsx2("div", { className: "flex-1", children: /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsxs2(Select, { onValueChange: onChange, ...field, children: [
                        /* @__PURE__ */ jsx2(
                          Select.Trigger,
                          {
                            className: "bg-ui-bg-base",
                            ref,
                            children: /* @__PURE__ */ jsx2(Select.Value, {})
                          }
                        ),
                        /* @__PURE__ */ jsx2(Select.Content, { children: stock_locations.map((l) => /* @__PURE__ */ jsx2(Select.Item, { value: l.id, children: l.name }, l.id)) })
                      ] }) }) })
                    ] }),
                    /* @__PURE__ */ jsx2(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsxs2(Form.Item, { className: "mt-8 pt-8", children: [
              /* @__PURE__ */ jsxs2("div", { className: "flex flex-row items-center", children: [
                /* @__PURE__ */ jsxs2("div", { className: "flex-1", children: [
                  /* @__PURE__ */ jsx2(Form.Label, { children: t("orders.allocateItems.itemsToAllocate") }),
                  /* @__PURE__ */ jsx2(Form.Hint, { children: t("orders.allocateItems.itemsToAllocateDesc") })
                ] }),
                /* @__PURE__ */ jsx2("div", { className: "flex-1", children: /* @__PURE__ */ jsx2(
                  Input2,
                  {
                    value: filterTerm,
                    onChange: (e) => setFilterTerm(e.target.value),
                    placeholder: t("orders.allocateItems.search"),
                    autoComplete: "off",
                    type: "search"
                  }
                ) })
              ] }),
              allocationError && /* @__PURE__ */ jsx2(Alert, { className: "mb-4", dismissible: true, variant: "error", children: allocationError }),
              /* @__PURE__ */ jsx2("div", { className: "flex flex-col gap-y-2", children: filteredItems.map((item) => /* @__PURE__ */ jsx2(
                OrderAllocateItemsItem,
                {
                  form,
                  item,
                  locationId: selectedLocationId,
                  onQuantityChange,
                  onToggleSelected
                },
                item.id
              )) })
            ] })
          ] })
        ] }) }) }) }),
        /* @__PURE__ */ jsx2(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx2(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx2(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: isMutating,
              disabled: !selectedLocationId || disableSubmit,
              children: t("orders.allocateItems.action")
            }
          )
        ] }) })
      ]
    }
  ) });
}
var resolveInventoryItemId2 = (link) => link.inventory_item?.id ?? link.inventory_item_id ?? null;
var clampToAvailable = (desired, link, locationId) => {
  if (!locationId) {
    return desired;
  }
  const level = link.inventory_item?.location_levels?.find(
    (l) => l.location_id === locationId
  );
  const available = level?.available_quantity ?? Number.MAX_SAFE_INTEGER;
  return Math.max(0, Math.min(desired, available));
};
function defaultAllocations(items, locationId) {
  const ret = {};
  items.forEach((item) => {
    const links = item.offer?.inventory_item_link ?? [];
    const hasInventoryKit = links.length > 1;
    const firstLink = links[0];
    const firstInventoryItemId = resolveInventoryItemId2(firstLink ?? {});
    const fulfillable = getFulfillableQuantity(
      item
    );
    if (hasInventoryKit) {
      ret[`${item.id}-`] = fulfillable;
      links.forEach((link) => {
        const id = resolveInventoryItemId2(link);
        if (!id) return;
        const required = link.required_quantity ?? 1;
        ret[`${item.id}-${id}`] = clampToAvailable(
          fulfillable * required,
          link,
          locationId
        );
      });
    } else {
      ret[`${item.id}-${firstInventoryItemId ?? ""}`] = clampToAvailable(
        fulfillable,
        firstLink ?? {},
        locationId
      );
    }
  });
  return ret;
}
function defaultSelected(items) {
  const ret = {};
  items.forEach((item) => {
    ret[item.id] = true;
  });
  return ret;
}

// src/pages/orders/[id]/allocate-items/index.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var Component2 = () => {
  const { id } = useParams();
  const { order, isLoading, isError, error } = useOrder(id, {
    // `*foo,*foo.bar` or `+foo.bar.baz` makes Medusa's query parser try
    // to look up a literal property `*items` / `+items` on Order and
    // 500. Use `<rel>.*` plus bare scalar names.
    fields: "currency_code,items.*,items.variant.*,items.variant.product.title,items.offer.*,items.offer.inventory_item_link.*,items.offer.inventory_item_link.required_quantity,items.offer.inventory_item_link.inventory_item.*,items.offer.inventory_item_link.inventory_item.location_levels.*,shipping_address.*"
  });
  if (isError) {
    throw error;
  }
  const ready = !isLoading && order;
  return /* @__PURE__ */ jsx3(RouteFocusModal, { children: ready && /* @__PURE__ */ jsx3(OrderAllocateItemsForm, { order }) });
};
export {
  Component2 as Component
};
