import {
  getFulfillableQuantity
} from "./chunk-RXM4B6HR.js";
import {
  getReservationsLimitCount
} from "./chunk-3KOTDGC2.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./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 {
  useShippingOptions
} from "./chunk-O4STPJR2.js";
import {
  useCreateOrderFulfillment,
  useOrder
} from "./chunk-R74OHYTB.js";
import {
  useReservationItems
} from "./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 {
  useProductVariant
} from "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/orders/order-create-fulfillment/order-create-fulfillments.tsx
import { useParams, useSearchParams } from "react-router-dom";

// src/pages/orders/order-create-fulfillment/components/order-create-fulfillment-form/order-create-fulfillment-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { Alert, Button, Select, Switch, toast } from "@medusajs/ui";
import { useForm, useWatch } from "react-hook-form";

// src/pages/orders/order-create-fulfillment/components/order-create-fulfillment-form/constants.ts
import { z } from "zod";
var CreateFulfillmentSchema = z.object({
  quantity: z.record(z.string(), z.number()),
  location_id: z.string(),
  shipping_option_id: z.string().optional(),
  send_notification: z.boolean().optional()
});

// src/pages/orders/order-create-fulfillment/components/order-create-fulfillment-form/order-create-fulfillment-item.tsx
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { clx, Input, Text, Tooltip } from "@medusajs/ui";
import { InformationCircleSolid } from "@medusajs/icons";
import { jsx, jsxs } from "react/jsx-runtime";
function OrderCreateFulfillmentItem({
  item,
  form,
  locationId,
  reservations,
  disabled
}) {
  const { t } = useTranslation();
  const { variant } = useProductVariant(
    item.product_id,
    item.variant_id,
    {
      fields: "*inventory,*inventory.location_levels,*inventory_items"
    },
    {
      enabled: !!item.variant
    }
  );
  const { availableQuantity, inStockQuantity } = useMemo(() => {
    if (!variant?.inventory_items?.length || !variant?.inventory?.length || !locationId) {
      return {};
    }
    const { inventory, inventory_items } = variant;
    const locationHasEveryInventoryItem = inventory.every(
      (i) => i.location_levels?.find((inv) => inv.location_id === locationId)
    );
    if (!locationHasEveryInventoryItem) {
      return {};
    }
    const inventoryItemRequiredQuantityMap = new Map(
      inventory_items.map((i) => [i.inventory_item_id, i.required_quantity])
    );
    const reservation = reservations?.find((r) => r.line_item_id === item.id);
    const iitemRequiredQuantity = inventory_items.find(
      (i) => i.inventory_item_id === reservation?.inventory_item_id
    )?.required_quantity;
    const reservedQuantityForItem = !reservation ? 0 : reservation?.quantity / (iitemRequiredQuantity || 1);
    const locationInventoryLevels = inventory.map((i) => {
      const level = i.location_levels?.find(
        (inv) => inv.location_id === locationId
      );
      const requiredQuantity = inventoryItemRequiredQuantityMap.get(i.id);
      if (!level || !requiredQuantity) {
        return {
          availableQuantity: Number.MAX_SAFE_INTEGER,
          stockedQuantity: Number.MAX_SAFE_INTEGER
        };
      }
      const availableQuantity2 = level.available_quantity / requiredQuantity;
      const stockedQuantity = level.stocked_quantity / requiredQuantity;
      return {
        availableQuantity: availableQuantity2,
        stockedQuantity
      };
    });
    const maxAvailableQuantity = Math.min(
      ...locationInventoryLevels.map((i) => i.availableQuantity)
    );
    const maxStockedQuantity = Math.min(
      ...locationInventoryLevels.map((i) => i.stockedQuantity)
    );
    if (maxAvailableQuantity === Number.MAX_SAFE_INTEGER || maxStockedQuantity === Number.MAX_SAFE_INTEGER) {
      return {};
    }
    return {
      availableQuantity: Math.floor(
        maxAvailableQuantity + reservedQuantityForItem
      ),
      inStockQuantity: Math.floor(maxStockedQuantity)
    };
  }, [variant, locationId, reservations]);
  const minValue = 0;
  const maxValue = Math.min(
    getFulfillableQuantity(item),
    availableQuantity || Number.MAX_SAFE_INTEGER
  );
  return /* @__PURE__ */ jsx(
    Form.Field,
    {
      control: form.control,
      name: `quantity.${item.id}`,
      rules: {
        required: true,
        min: minValue,
        max: maxValue
      },
      render: ({ field }) => {
        return /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl", "data-testid": `order-create-fulfillment-item-${item.id}`, children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-row items-center", "data-testid": `order-create-fulfillment-item-${item.id}-content`, children: [
            disabled && /* @__PURE__ */ jsx("div", { className: "inline-flex items-center ml-4", "data-testid": `order-create-fulfillment-item-${item.id}-disabled-indicator`, children: /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("orders.fulfillment.disabledItemTooltip"),
                side: "top",
                children: /* @__PURE__ */ jsx(InformationCircleSolid, { className: "text-ui-tag-orange-icon" })
              }
            ) }),
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: clx(
                  "flex flex-col flex-1 gap-x-2 gap-y-2 p-3 text-sm sm:flex-row",
                  disabled && "opacity-50 pointer-events-none"
                ),
                "data-testid": `order-create-fulfillment-item-${item.id}-details`,
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center gap-x-3", "data-testid": `order-create-fulfillment-item-${item.id}-info`, children: [
                    /* @__PURE__ */ jsx(Thumbnail, { src: item.thumbnail, "data-testid": `order-create-fulfillment-item-${item.id}-thumbnail` }),
                    /* @__PURE__ */ jsxs("div", { className: "flex flex-col", "data-testid": `order-create-fulfillment-item-${item.id}-text`, children: [
                      /* @__PURE__ */ jsxs("div", { "data-testid": `order-create-fulfillment-item-${item.id}-title`, children: [
                        /* @__PURE__ */ jsx(Text, { className: "txt-small", as: "span", weight: "plus", children: item.title }),
                        item.variant_sku && /* @__PURE__ */ jsxs("span", { "data-testid": `order-create-fulfillment-item-${item.id}-sku`, children: [
                          "(",
                          item.variant_sku,
                          ")"
                        ] })
                      ] }),
                      /* @__PURE__ */ jsx(Text, { as: "div", className: "text-ui-fg-subtle txt-small", "data-testid": `order-create-fulfillment-item-${item.id}-variant-title`, children: item.variant_title })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center gap-x-1", "data-testid": `order-create-fulfillment-item-${item.id}-quantities`, children: [
                    /* @__PURE__ */ jsx("div", { className: "mr-2 block h-[16px] w-[2px] bg-gray-200" }),
                    /* @__PURE__ */ jsxs("div", { className: "text-small flex flex-1 flex-col", "data-testid": `order-create-fulfillment-item-${item.id}-available`, children: [
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", "data-testid": `order-create-fulfillment-item-${item.id}-available-label`, children: t("orders.fulfillment.available") }),
                      /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle", "data-testid": `order-create-fulfillment-item-${item.id}-available-value`, children: availableQuantity || "N/A" })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center gap-x-1", "data-testid": `order-create-fulfillment-item-${item.id}-in-stock`, children: [
                      /* @__PURE__ */ jsx("div", { className: "mr-2 block h-[16px] w-[2px] bg-gray-200" }),
                      /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                        /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle font-medium", "data-testid": `order-create-fulfillment-item-${item.id}-in-stock-label`, children: t("orders.fulfillment.inStock") }),
                        /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-subtle", "data-testid": `order-create-fulfillment-item-${item.id}-in-stock-value`, children: [
                          inStockQuantity || "N/A",
                          " ",
                          inStockQuantity && /* @__PURE__ */ jsxs("span", { className: "font-medium text-red-500", "data-testid": `order-create-fulfillment-item-${item.id}-in-stock-reserved`, children: [
                            "-",
                            form.getValues(`quantity.${item.id}`)
                          ] })
                        ] })
                      ] })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center gap-1", "data-testid": `order-create-fulfillment-item-${item.id}-quantity-input-section`, children: [
                      /* @__PURE__ */ jsxs(Form.Item, { "data-testid": `order-create-fulfillment-item-${item.id}-quantity-item`, children: [
                        /* @__PURE__ */ jsx(Form.Control, { "data-testid": `order-create-fulfillment-item-${item.id}-quantity-control`, children: /* @__PURE__ */ jsx(
                          Input,
                          {
                            className: "bg-ui-bg-base txt-small w-[50px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
                            type: "number",
                            ...field,
                            onChange: (e) => {
                              const val = e.target.value === "" ? null : Number(e.target.value);
                              field.onChange(val);
                              if (!isNaN(val)) {
                                if (val < minValue || val > maxValue) {
                                  form.setError(`quantity.${item.id}`, {
                                    type: "manual",
                                    message: t(
                                      "orders.fulfillment.error.wrongQuantity",
                                      {
                                        count: maxValue,
                                        number: maxValue
                                      }
                                    )
                                  });
                                } else {
                                  form.clearErrors(`quantity.${item.id}`);
                                }
                              }
                            },
                            "data-testid": `order-create-fulfillment-item-${item.id}-quantity-input`
                          }
                        ) }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": `order-create-fulfillment-item-${item.id}-quantity-error` })
                      ] }),
                      /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-subtle", "data-testid": `order-create-fulfillment-item-${item.id}-quantity-label`, children: [
                        "/ ",
                        item.quantity,
                        " ",
                        t("fields.qty")
                      ] })
                    ] })
                  ] })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx(Form.ErrorMessage, { className: "flex justify-end pr-3 pb-2" })
        ] });
      }
    }
  );
}

// src/pages/orders/order-create-fulfillment/components/order-create-fulfillment-form/order-create-fulfillment-form.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
function OrderCreateFulfillmentForm({
  order,
  requiresShipping
}) {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const direction = useDocumentDirection();
  const { mutateAsync: createOrderFulfillment, isPending: isMutating } = useCreateOrderFulfillment(order.id);
  const { reservations } = useReservationItems({
    line_item_id: order.items.map((i) => i.id),
    limit: getReservationsLimitCount(order)
  });
  const stockLocations = useComboboxData({
    queryFn: (params) => sdk.admin.stockLocations.query(params),
    queryKey: ["stock_locations"],
    getOptions: (data) => data.stock_locations.map((location) => ({
      label: location.name,
      value: location.id
    }))
  });
  const [fulfillableItems, setFulfillableItems] = useState(
    () => (order.items || []).filter(
      (item) => item.requires_shipping === requiresShipping && getFulfillableQuantity(item) > 0
    )
  );
  const form = useForm({
    defaultValues: {
      quantity: fulfillableItems.reduce(
        (acc, item) => {
          acc[item.id] = getFulfillableQuantity(item);
          return acc;
        },
        {}
      ),
      send_notification: !order.no_notification
    },
    resolver: zodResolver(CreateFulfillmentSchema)
  });
  const selectedLocationId = useWatch({
    name: "location_id",
    control: form.control
  });
  const { shipping_options = [], isLoading: isShippingOptionsLoading } = useShippingOptions({
    stock_location_id: selectedLocationId,
    // is_return: false, // TODO: 500 when enabled
    fields: "+service_zone.fulfillment_set.location.id"
  });
  const shippingOptionId = useWatch({
    name: "shipping_option_id",
    control: form.control
  });
  const handleSubmit = form.handleSubmit(async (data) => {
    const selectedShippingOption = shipping_options.find(
      (o) => o.id === shippingOptionId
    );
    if (!selectedShippingOption) {
      form.setError("shipping_option_id", {
        type: "manual",
        message: t("orders.fulfillment.error.noShippingOption")
      });
      return;
    }
    if (!selectedLocationId) {
      form.setError("location_id", {
        type: "manual",
        message: t("orders.fulfillment.error.noLocation")
      });
      return;
    }
    let items = Object.entries(data.quantity).map(([id, quantity]) => ({
      id,
      quantity
    })).filter(({ quantity }) => !!quantity);
    if (requiresShipping) {
      const selectedShippingProfileId = selectedShippingOption?.shipping_profile_id;
      const itemShippingProfileMap = order.items.reduce((acc, item) => {
        acc[item.id] = item.variant?.product?.shipping_profile?.id;
        return acc;
      }, {});
      items = items.filter(
        ({ id }) => itemShippingProfileMap[id] === selectedShippingProfileId
      );
    }
    const payload = {
      location_id: selectedLocationId,
      shipping_option_id: shippingOptionId,
      no_notification: !data.send_notification,
      items
    };
    try {
      await createOrderFulfillment(payload);
      toast.success(t("orders.fulfillment.toast.created"));
      handleSuccess(`/orders/${order.id}`);
    } catch (e) {
      toast.error(e.message);
    }
  });
  useEffect(() => {
    if (shipping_options?.length) {
      const initialShippingOptionId = order.shipping_methods?.[0]?.shipping_option_id;
      if (initialShippingOptionId) {
        const shippingOption = shipping_options.find(
          (o) => o.id === initialShippingOptionId
        );
        if (shippingOption) {
          const locationId = shippingOption.service_zone.fulfillment_set.location.id;
          form.setValue("location_id", locationId);
          form.setValue(
            "shipping_option_id",
            initialShippingOptionId || void 0
          );
        }
      }
    }
  }, [shipping_options]);
  const fulfilledQuantityArray = (order.items || []).map(
    (item) => item.requires_shipping === requiresShipping && item.detail.fulfilled_quantity
  );
  useEffect(() => {
    const itemsToFulfill = order?.items?.filter(
      (item) => item.requires_shipping === requiresShipping && getFulfillableQuantity(item) > 0
    ) || [];
    setFulfillableItems(itemsToFulfill);
    if (itemsToFulfill.length) {
      form.clearErrors("root");
    } else {
      form.setError("root", {
        type: "manual",
        message: t("orders.fulfillment.error.noItems")
      });
    }
    const quantityMap = itemsToFulfill.reduce(
      (acc, item) => {
        acc[item.id] = getFulfillableQuantity(item);
        return acc;
      },
      {}
    );
    form.setValue("quantity", quantityMap);
  }, [...fulfilledQuantityArray, requiresShipping]);
  const differentOptionSelected = shippingOptionId && order.shipping_methods?.[0]?.shipping_option_id !== shippingOptionId;
  return /* @__PURE__ */ jsx2(RouteFocusModal.Form, { form, "data-testid": "order-create-fulfillment-form", children: /* @__PURE__ */ jsxs2(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      "data-testid": "order-create-fulfillment-form",
      children: [
        /* @__PURE__ */ jsx2(RouteFocusModal.Header, { "data-testid": "order-create-fulfillment-header" }),
        /* @__PURE__ */ jsx2(RouteFocusModal.Body, { className: "flex h-full w-full flex-col items-center divide-y overflow-y-auto", "data-testid": "order-create-fulfillment-body", children: /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col items-center overflow-auto p-16", "data-testid": "order-create-fulfillment-form-content", 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 divide-y divide-dashed", children: [
          /* @__PURE__ */ jsx2("div", { className: "pb-8", "data-testid": "order-create-fulfillment-location-section", children: /* @__PURE__ */ jsx2(
            Form.Field,
            {
              control: form.control,
              name: "location_id",
              render: ({ field: { ...field } }) => {
                return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "order-create-fulfillment-location-item", children: [
                  /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-2 xl:flex-row xl:items-center", children: [
                    /* @__PURE__ */ jsxs2("div", { className: "flex-1", children: [
                      /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "order-create-fulfillment-location-label", children: t("fields.location") }),
                      /* @__PURE__ */ jsx2(Form.Hint, { "data-testid": "order-create-fulfillment-location-hint", children: t("orders.fulfillment.locationDescription") })
                    ] }),
                    /* @__PURE__ */ jsx2("div", { className: "flex-1", children: /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "order-create-fulfillment-location-control", children: /* @__PURE__ */ jsx2(
                      Combobox,
                      {
                        ...field,
                        options: stockLocations.options,
                        searchValue: stockLocations.searchValue,
                        onSearchValueChange: stockLocations.onSearchValueChange,
                        disabled: stockLocations.disabled,
                        "data-testid": "order-create-fulfillment-location-combobox"
                      }
                    ) }) })
                  ] }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "order-create-fulfillment-location-error" })
                ] });
              }
            }
          ) }),
          /* @__PURE__ */ jsxs2("div", { className: "py-8", "data-testid": "order-create-fulfillment-shipping-section", children: [
            /* @__PURE__ */ jsx2(
              Form.Field,
              {
                control: form.control,
                name: "shipping_option_id",
                render: ({ field: { onChange, ref, ...field } }) => {
                  return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "order-create-fulfillment-shipping-item", children: [
                    /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-2 xl:flex-row xl:items-center", children: [
                      /* @__PURE__ */ jsxs2("div", { className: "flex-1", children: [
                        /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "order-create-fulfillment-shipping-label", children: t("fields.shippingMethod") }),
                        /* @__PURE__ */ jsx2(Form.Hint, { "data-testid": "order-create-fulfillment-shipping-hint", children: t("orders.fulfillment.methodDescription") })
                      ] }),
                      /* @__PURE__ */ jsx2("div", { className: "flex-1", children: /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "order-create-fulfillment-shipping-control", children: /* @__PURE__ */ jsxs2(
                        Select,
                        {
                          dir: direction,
                          onValueChange: onChange,
                          ...field,
                          disabled: !selectedLocationId,
                          "data-testid": "order-create-fulfillment-shipping-select",
                          children: [
                            /* @__PURE__ */ jsx2(
                              Select.Trigger,
                              {
                                className: "bg-ui-bg-base",
                                ref,
                                "data-testid": "order-create-fulfillment-shipping-trigger",
                                children: isShippingOptionsLoading ? /* @__PURE__ */ jsxs2("span", { className: "text-right", "data-testid": "order-create-fulfillment-form-shipping-select-loading", children: [
                                  t("labels.loading"),
                                  "..."
                                ] }) : /* @__PURE__ */ jsx2(Select.Value, { "data-testid": "order-create-fulfillment-form-shipping-select-value" })
                              }
                            ),
                            /* @__PURE__ */ jsx2(Select.Content, { "data-testid": "order-create-fulfillment-shipping-content", children: shipping_options.map((o) => /* @__PURE__ */ jsx2(Select.Item, { value: o.id, "data-testid": `order-create-fulfillment-shipping-option-${o.id}`, children: o.name }, o.id)) })
                          ]
                        }
                      ) }) })
                    ] }),
                    /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "order-create-fulfillment-shipping-error" })
                  ] });
                }
              }
            ),
            differentOptionSelected && /* @__PURE__ */ jsxs2(Alert, { className: "mt-4 p-4", variant: "warning", "data-testid": "order-create-fulfillment-shipping-warning", children: [
              /* @__PURE__ */ jsx2("span", { className: "-mt-[3px] block font-medium", "data-testid": "order-create-fulfillment-form-shipping-warning-title", children: t("labels.beaware") }),
              /* @__PURE__ */ jsx2("span", { className: "text-ui-fg-muted", "data-testid": "order-create-fulfillment-form-shipping-warning-message", children: t("orders.fulfillment.differentOptionSelected") })
            ] })
          ] }),
          /* @__PURE__ */ jsxs2("div", { "data-testid": "order-create-fulfillment-items-section", children: [
            /* @__PURE__ */ jsxs2(Form.Item, { className: "mt-8", "data-testid": "order-create-fulfillment-items-item", children: [
              /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "order-create-fulfillment-items-label", children: t("orders.fulfillment.itemsToFulfill") }),
              /* @__PURE__ */ jsx2(Form.Hint, { "data-testid": "order-create-fulfillment-items-hint", children: t("orders.fulfillment.itemsToFulfillDesc") }),
              /* @__PURE__ */ jsx2("div", { className: "flex flex-col gap-y-1", "data-testid": "order-create-fulfillment-items-list", children: fulfillableItems.map((item) => {
                const isShippingProfileMatching = shipping_options.find(
                  (o) => o.id === shippingOptionId
                )?.shipping_profile_id === item.variant?.product?.shipping_profile?.id;
                return /* @__PURE__ */ jsx2(
                  OrderCreateFulfillmentItem,
                  {
                    form,
                    item,
                    locationId: selectedLocationId,
                    disabled: requiresShipping && !isShippingProfileMatching,
                    reservations
                  },
                  item.id
                );
              }) })
            ] }),
            form.formState.errors.root && /* @__PURE__ */ jsx2(
              Alert,
              {
                variant: "error",
                dismissible: false,
                className: "flex items-center",
                classNameInner: "flex justify-between flex-1 items-center",
                "data-testid": "order-create-fulfillment-items-error",
                children: form.formState.errors.root.message
              }
            )
          ] }),
          /* @__PURE__ */ jsx2("div", { className: "mt-8 pt-8 ", "data-testid": "order-create-fulfillment-notification-section", children: /* @__PURE__ */ jsx2(
            Form.Field,
            {
              control: form.control,
              name: "send_notification",
              render: ({ field: { onChange, value, ...field } }) => {
                return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "order-create-fulfillment-notification-item", children: [
                  /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between", "data-testid": "order-create-fulfillment-form-notification-control", children: [
                    /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "order-create-fulfillment-notification-label", children: t("orders.returns.sendNotification") }),
                    /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "order-create-fulfillment-notification-control", children: /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsx2(
                      Switch,
                      {
                        dir: "ltr",
                        className: "rtl:rotate-180",
                        checked: !!value,
                        onCheckedChange: onChange,
                        ...field,
                        "data-testid": "order-create-fulfillment-notification-switch"
                      }
                    ) }) })
                  ] }),
                  /* @__PURE__ */ jsx2(Form.Hint, { className: "!mt-1", "data-testid": "order-create-fulfillment-notification-hint", children: t("orders.fulfillment.sendNotificationHint") }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "order-create-fulfillment-notification-error" })
                ] });
              }
            }
          ) })
        ] }) }) }) }),
        /* @__PURE__ */ jsx2(RouteFocusModal.Footer, { "data-testid": "order-create-fulfillment-footer", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", "data-testid": "order-create-fulfillment-form-footer-actions", children: [
          /* @__PURE__ */ jsx2(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { size: "small", variant: "secondary", "data-testid": "order-create-fulfillment-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx2(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: isMutating,
              disabled: !shippingOptionId,
              "data-testid": "order-create-fulfillment-create-button",
              children: t("orders.fulfillment.create")
            }
          )
        ] }) })
      ]
    }
  ) });
}

// src/pages/orders/order-create-fulfillment/order-create-fulfillments.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
function OrderCreateFulfillment() {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const requiresShipping = searchParams.get("requires_shipping") === "true";
  const { order, isLoading, isError, error } = useOrder(id, {
    fields: "currency_code,*items,*items.variant,+items.variant.product.shipping_profile.id,*shipping_address,+shipping_methods.shipping_option_id"
  });
  if (isError) {
    throw error;
  }
  const ready = !isLoading && order;
  return /* @__PURE__ */ jsx3(RouteFocusModal, { "data-testid": "order-create-fulfillment-modal", children: ready && /* @__PURE__ */ jsx3(
    OrderCreateFulfillmentForm,
    {
      order,
      requiresShipping
    }
  ) });
}
export {
  OrderCreateFulfillment as Component
};
