import {
  OFFER_VARIANT_DETAIL_FIELDS
} from "./chunk-XQUF3WIS.js";
import {
  DataGrid,
  DataGridReadonlyCell,
  DataGridTogglableNumberCell,
  createDataGridHelper
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import {
  useStockLocations
} from "./chunk-O72AIZUN.js";
import {
  useOffer
} from "./chunk-5DKUSZQ7.js";
import {
  useBatchInventoryItemsLocationLevels
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/offers/[id]/variants/[offer_id]/inventory/index.tsx
import { useTranslation as useTranslation3 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/offers/[id]/inventory/inventory-batch-form/inventory-batch-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, toast, usePrompt } from "@medusajs/ui";
import { useMemo as useMemo2, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/offers/[id]/inventory/inventory-batch-form/hooks/use-offer-stock-columns.tsx
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var helper = createDataGridHelper();
var useOfferStockColumns = (locations = []) => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      helper.column({
        id: "title",
        name: t("fields.title"),
        header: t("fields.title"),
        cell: (context) => {
          const item = context.row.original;
          return /* @__PURE__ */ jsx(DataGridReadonlyCell, { context, color: "normal", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2 overflow-hidden", children: [
            /* @__PURE__ */ jsx(Thumbnail, { src: item.thumbnail ?? null }),
            /* @__PURE__ */ jsx("span", { className: "truncate", title: item.title ?? "", children: item.title || "-" })
          ] }) });
        },
        disableHiding: true
      }),
      helper.column({
        id: "sku",
        name: t("offers.fields.sku"),
        header: t("offers.fields.sku"),
        cell: (context) => {
          const item = context.row.original;
          return /* @__PURE__ */ jsx(DataGridReadonlyCell, { context, color: "normal", children: item.sku || "-" });
        },
        disableHiding: true
      }),
      ...locations.map(
        (location) => helper.column({
          id: `location_${location.id}`,
          name: location.name,
          header: location.name,
          field: (context) => `inventory_items.${context.row.original.id}.locations.${location.id}`,
          type: "togglable-number",
          cell: (context) => /* @__PURE__ */ jsx(
            DataGridTogglableNumberCell,
            {
              context,
              disabledToggleTooltip: t("inventory.stock.disabledToggleTooltip"),
              placeholder: t("inventory.stock.placeholder")
            }
          )
        })
      )
    ],
    [locations, t]
  );
};

// src/pages/offers/[id]/inventory/inventory-batch-form/schema.ts
import { z } from "zod";
var LocationQuantitySchema = z.object({
  id: z.string().optional(),
  quantity: z.union([z.number(), z.string()]),
  checked: z.boolean(),
  disabledToggle: z.boolean()
});
var InventoryItemLocationsSchema = z.record(
  z.string(),
  LocationQuantitySchema
);
var InventoryItemSchema = z.object({
  locations: InventoryItemLocationsSchema
});
var OfferStockSchema = z.object({
  inventory_items: z.record(z.string(), InventoryItemSchema)
});

// src/pages/offers/[id]/inventory/inventory-batch-form/inventory-batch-form.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var InventoryBatchForm = ({
  offer,
  locations
}) => {
  const { t } = useTranslation2();
  const { handleSuccess, setCloseOnEscape } = useRouteModal();
  const prompt = usePrompt();
  const [isPromptOpen, setIsPromptOpen] = useState(false);
  const rows = useMemo2(() => buildRows(offer), [offer]);
  const defaults = useMemo2(
    () => getDefaultValue(offer, locations),
    [offer, locations]
  );
  const initialValues = useRef(defaults);
  const form = useForm({
    defaultValues: defaults,
    resolver: zodResolver(OfferStockSchema)
  });
  const columns = useOfferStockColumns(locations);
  const { mutateAsync, isPending } = useBatchInventoryItemsLocationLevels();
  const onSubmit = form.handleSubmit(async (data) => {
    const payload = {
      create: [],
      update: [],
      delete: [],
      force: true
    };
    for (const [inventory_item_id, item] of Object.entries(
      data.inventory_items
    )) {
      for (const [location_id, level] of Object.entries(item.locations)) {
        if (level.id) {
          const wasChecked = initialValues.current.inventory_items?.[inventory_item_id]?.locations?.[location_id]?.checked;
          if (wasChecked && !level.checked) {
            payload.delete.push(level.id);
          } else {
            const newQuantity = level.quantity !== "" ? castNumber(level.quantity) : 0;
            const originalQuantity = initialValues.current.inventory_items?.[inventory_item_id]?.locations?.[location_id]?.quantity;
            if (newQuantity !== originalQuantity) {
              payload.update.push({
                inventory_item_id,
                location_id,
                stocked_quantity: newQuantity
              });
            }
          }
        }
        if (!level.id && level.quantity !== "") {
          payload.create.push({
            inventory_item_id,
            location_id,
            stocked_quantity: castNumber(level.quantity)
          });
        }
      }
    }
    if (payload.delete && payload.delete.length > 0) {
      setIsPromptOpen(true);
      const confirm = await prompt({
        title: t("general.areYouSure"),
        description: t("inventory.stock.disablePrompt", {
          count: payload.delete.length
        }),
        confirmText: t("actions.continue"),
        cancelText: t("actions.cancel"),
        variant: "confirmation"
      });
      setIsPromptOpen(false);
      if (!confirm) return;
    }
    await mutateAsync(payload, {
      onSuccess: () => {
        toast.success(t("offers.inventory.successToast"));
        handleSuccess();
      },
      onError: (error) => toast.error(error.message)
    });
  });
  return /* @__PURE__ */ jsx2(RouteFocusModal.Form, { form, "data-testid": "offer-inventory-batch-form", children: /* @__PURE__ */ jsxs2(KeyboundForm, { onSubmit, className: "flex size-full flex-col", children: [
    /* @__PURE__ */ jsx2(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx2(RouteFocusModal.Body, { className: "flex flex-col overflow-hidden", children: /* @__PURE__ */ jsx2(
      DataGrid,
      {
        state: form,
        columns,
        data: rows,
        onEditingChange: (editing) => setCloseOnEscape(!editing),
        disableInteractions: isPending || isPromptOpen,
        multiColumnSelection: true
      }
    ) }),
    /* @__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, { variant: "secondary", size: "small", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx2(Button, { type: "submit", size: "small", isLoading: isPending, children: t("actions.save") })
    ] }) })
  ] }) });
};
function buildRows(offer) {
  return (offer.inventory_item_link ?? []).map((link) => {
    const item = link.inventory_item;
    if (!item?.id) return null;
    return {
      id: item.id,
      title: item.title,
      sku: item.sku,
      thumbnail: null
    };
  }).filter((row) => row !== null);
}
function getDefaultValue(offer, locations) {
  const inventory_items = {};
  for (const link of offer.inventory_item_link ?? []) {
    const item = link.inventory_item;
    if (!item?.id) continue;
    const locationMap = {};
    for (const location of locations) {
      const level = item.location_levels?.find(
        (l) => l.location_id === location.id
      );
      locationMap[location.id] = {
        id: level?.id,
        quantity: level?.stocked_quantity !== void 0 && level?.stocked_quantity !== null ? level.stocked_quantity : "",
        checked: !!level,
        disabledToggle: (level?.incoming_quantity ?? 0) > 0 || (level?.reserved_quantity ?? 0) > 0
      };
    }
    inventory_items[item.id] = { locations: locationMap };
  }
  return { inventory_items };
}

// src/pages/offers/[id]/variants/[offer_id]/inventory/index.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var OfferVariantInventoryPage = () => {
  const { offer_id } = useParams();
  const { t } = useTranslation3();
  const { offer, isPending, isError, error } = useOffer(offer_id, {
    fields: OFFER_VARIANT_DETAIL_FIELDS
  });
  const { stock_locations, isPending: isLocationsPending } = useStockLocations({
    limit: 100
  });
  if (isError) throw error;
  const ready = !isPending && !!offer && !isLocationsPending && !!stock_locations;
  return /* @__PURE__ */ jsxs3(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx3(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx3("span", { className: "sr-only", children: t("offers.inventory.header") }) }),
    /* @__PURE__ */ jsx3(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx3("span", { className: "sr-only", children: t("offers.inventory.description") }) }),
    ready && /* @__PURE__ */ jsx3(
      InventoryBatchForm,
      {
        offer,
        locations: stock_locations
      }
    )
  ] });
};
var Component = OfferVariantInventoryPage;
export {
  Component,
  OfferVariantInventoryPage
};
