import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-PBQ5M44A.js";
import "./chunk-OH4AABUT.js";
import "./chunk-YKDEE7ZL.js";
import "./chunk-AEMDNTW5.js";
import "./chunk-LYD3C73Z.js";
import "./chunk-7O5NDICV.js";
import "./chunk-46M463BR.js";
import "./chunk-YFRC6GEN.js";
import "./chunk-N6SI4IIT.js";
import "./chunk-JPNPTILP.js";
import "./chunk-DAXXLQKB.js";
import "./chunk-OHOWEMHO.js";
import "./chunk-GKGLVDDV.js";
import "./chunk-WJJXUXSO.js";
import "./chunk-LAPEZATU.js";
import "./chunk-DBNPVU3L.js";
import "./chunk-U7WZYWGA.js";
import "./chunk-ZN7LWXVC.js";
import "./chunk-VYMODH6P.js";
import "./chunk-LEG67A2R.js";
import "./chunk-PRBE5CM3.js";
import "./chunk-5TRY5IMZ.js";
import "./chunk-TAKEQAZZ.js";
import "./chunk-B6FG7A6W.js";
import {
  useStockLocation
} from "./chunk-EPHVGD5Z.js";
import "./chunk-ESPLVOFC.js";
import "./chunk-FXWKGNRV.js";
import "./chunk-VDKOJ5WD.js";
import "./chunk-DL2ZIXBO.js";
import "./chunk-Z2QQZOG3.js";
import {
  useInventoryItem,
  useUpdateInventoryLevel
} from "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/inventory/inventory-detail/components/adjust-inventory/components/adjust-inventory-form.tsx
import { Button, Input, Text, toast } from "@medusajs/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";

// src/lib/sanitize-number-input.ts
var DISALLOWED_KEYS = ["e", "E", "-", "+"];
function sanitizeNumberInput(e, disallowedKeys) {
  if ([...DISALLOWED_KEYS, ...disallowedKeys || []].some((key) => key === e.key)) {
    e.preventDefault();
  }
}

// src/pages/inventory/inventory-detail/components/adjust-inventory/components/adjust-inventory-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var AttributeGridRow = ({
  title,
  value,
  testId
}) => {
  return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 divide-x", "data-testid": testId ? `${testId}-row` : void 0, children: [
    /* @__PURE__ */ jsx(Text, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": testId ? `${testId}-label` : void 0, children: title }),
    /* @__PURE__ */ jsx(Text, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": testId ? `${testId}-value` : void 0, children: value })
  ] });
};
var AdjustInventoryForm = ({
  item,
  level,
  location
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const AdjustInventorySchema = z.object({
    stocked_quantity: z.union([z.number(), z.string()])
  }).superRefine((data, ctx) => {
    const quantity = data.stocked_quantity ? castNumber(data.stocked_quantity) : null;
    if (quantity === null) {
      ctx.addIssue({
        code: z.ZodIssueCode.invalid_type,
        expected: "number",
        received: "undefined",
        path: ["stocked_quantity"]
      });
      return;
    }
    if (quantity < level.reserved_quantity) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: t("inventory.adjustInventory.errors.stockedQuantity", {
          quantity: level.reserved_quantity
        }),
        path: ["stocked_quantity"]
      });
    }
  });
  const form = useForm({
    defaultValues: {
      stocked_quantity: level.stocked_quantity
    },
    resolver: zodResolver(AdjustInventorySchema)
  });
  const stockedQuantityUpdate = useWatch({
    control: form.control,
    name: "stocked_quantity"
  });
  const availableQuantity = stockedQuantityUpdate ? castNumber(stockedQuantityUpdate) - level.reserved_quantity : 0 - level.reserved_quantity;
  const { mutateAsync, isPending: isLoading } = useUpdateInventoryLevel(
    item.id,
    level.location_id
  );
  const handleSubmit = form.handleSubmit(async (value) => {
    await mutateAsync(
      {
        stocked_quantity: castNumber(value.stocked_quantity)
      },
      {
        onSuccess: () => {
          toast.success(t("inventory.toast.updateLevel"));
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "inventory-adjust-inventory-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      "data-testid": "inventory-adjust-inventory-keybound-form",
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-8 overflow-auto", "data-testid": "inventory-adjust-inventory-form-body", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid grid-rows-4 divide-y rounded-lg border text-ui-fg-subtle shadow-elevation-card-rest", "data-testid": "inventory-adjust-inventory-form-info-grid", children: [
            /* @__PURE__ */ jsx(
              AttributeGridRow,
              {
                title: t("fields.title"),
                value: item.title ?? "-",
                testId: "inventory-adjust-inventory-form-item-title"
              }
            ),
            /* @__PURE__ */ jsx(
              AttributeGridRow,
              {
                title: t("fields.sku"),
                value: item.sku,
                testId: "inventory-adjust-inventory-form-item-sku"
              }
            ),
            /* @__PURE__ */ jsx(
              AttributeGridRow,
              {
                title: t("locations.domain"),
                value: location.name,
                testId: "inventory-adjust-inventory-form-location"
              }
            ),
            /* @__PURE__ */ jsx(
              AttributeGridRow,
              {
                title: t("inventory.reserved"),
                value: level.reserved_quantity,
                testId: "inventory-adjust-inventory-form-reserved"
              }
            ),
            /* @__PURE__ */ jsx(
              AttributeGridRow,
              {
                title: t("inventory.available"),
                value: availableQuantity,
                testId: "inventory-adjust-inventory-form-available"
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "stocked_quantity",
              render: ({ field: { onChange, value, ...field } }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "inventory-adjust-inventory-form-stocked-quantity-item", children: [
                  /* @__PURE__ */ jsx(Form.Label, { "data-testid": "inventory-adjust-inventory-form-stocked-quantity-label", children: t("fields.inStock") }),
                  /* @__PURE__ */ jsx(Form.Control, { "data-testid": "inventory-adjust-inventory-form-stocked-quantity-control", children: /* @__PURE__ */ jsx("div", { "data-testid": "inventory-adjust-inventory-form-stocked-quantity-input-wrapper", children: /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "number",
                      value,
                      onChange,
                      onKeyDown: (e) => sanitizeNumberInput(e, [",", "."]),
                      ...field,
                      "data-testid": "inventory-adjust-inventory-form-stocked-quantity-input"
                    }
                  ) }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "inventory-adjust-inventory-form-stocked-quantity-error" })
                ] });
              }
            }
          )
        ] }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { "data-testid": "inventory-adjust-inventory-form-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", "data-testid": "inventory-adjust-inventory-form-footer-actions", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, "data-testid": "inventory-adjust-inventory-form-cancel-button-wrapper", children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "small", "data-testid": "inventory-adjust-inventory-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { type: "submit", size: "small", isLoading, "data-testid": "inventory-adjust-inventory-form-save-button", children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var AdjustInventoryDrawer = () => {
  const { id, location_id } = useParams();
  const { t } = useTranslation2();
  const {
    inventory_item: inventoryItem,
    isPending: isLoading,
    isError,
    error
  } = useInventoryItem(id);
  const inventoryLevel = inventoryItem?.location_levels.find(
    (level) => level.location_id === location_id
  );
  const { stock_location, isLoading: isLoadingLocation } = useStockLocation(
    location_id
  );
  const ready = !isLoading && inventoryItem && inventoryLevel && !isLoadingLocation && stock_location;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { "data-testid": "inventory-adjust-inventory-drawer", children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { "data-testid": "inventory-adjust-inventory-drawer-header", children: /* @__PURE__ */ jsx2(Heading, { "data-testid": "inventory-adjust-inventory-drawer-title", children: t("inventory.manageLocationQuantity") }) }),
    ready && /* @__PURE__ */ jsx2(
      AdjustInventoryForm,
      {
        item: inventoryItem,
        level: inventoryLevel,
        location: stock_location
      }
    )
  ] });
};
export {
  AdjustInventoryDrawer as Component
};
