import {
  OFFER_PRODUCT_DETAIL_FIELDS
} from "./chunk-XQUF3WIS.js";
import {
  DataGrid,
  createDataGridHelper,
  createDataGridLocationStockColumns
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.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 {
  offerQueryKeys
} from "./chunk-5DKUSZQ7.js";
import {
  productsQueryKeys,
  useBatchInventoryItemsLocationLevels,
  useProduct
} from "./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/offers/[id]/edit-stock/index.tsx
import { Button, toast } from "@medusajs/ui";
import { useMemo, useRef } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var castNumber = (v) => v === "" || v === null || v === void 0 ? 0 : Number(v) || 0;
var buildRows = (product, locations) => (product.variants ?? []).flatMap(
  (variant) => (variant.offers ?? []).map((offer) => {
    const link = offer.inventory_item_link?.[0];
    const levels = link?.inventory_item?.location_levels ?? [];
    const inventory = {};
    for (const loc of locations) {
      const level = levels.find((l) => l.location_id === loc.id);
      inventory[loc.id] = level ? {
        checked: true,
        quantity: level.stocked_quantity ?? 0,
        id: level.id ?? void 0
      } : { checked: false, quantity: "" };
    }
    return {
      offer_id: offer.id,
      inventory_item_id: link?.inventory_item_id ?? null,
      variant_title: variant.title ?? "",
      product_thumbnail: product.thumbnail ?? null,
      sku: offer.sku ?? variant.sku ?? null,
      inventory
    };
  })
);
var columnHelper = createDataGridHelper();
var useColumns = ({
  stockLocations
}) => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.column({
        id: "title",
        header: t("fields.title"),
        cell: (context) => {
          const entity = context.row.original;
          return /* @__PURE__ */ jsx(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full items-center gap-x-2 overflow-hidden", children: [
            /* @__PURE__ */ jsx(Thumbnail, { src: entity.product_thumbnail ?? null }),
            /* @__PURE__ */ jsx("span", { className: "truncate", title: entity.variant_title, children: entity.variant_title })
          ] }) });
        },
        disableHiding: true
      }),
      columnHelper.column({
        id: "sku",
        name: t("fields.sku"),
        header: t("fields.sku"),
        cell: (context) => /* @__PURE__ */ jsx(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsx("span", { className: "truncate", children: context.row.original.sku ?? "-" }) })
      }),
      ...createDataGridLocationStockColumns({
        stockLocations,
        getFieldName: (context, index) => {
          const location = stockLocations[index];
          if (!location) return null;
          return `rows.${context.row.index}.inventory.${location.id}`;
        },
        t
      })
    ],
    [t, stockLocations]
  );
};
var EditStockGrid = ({
  product,
  productId,
  locations
}) => {
  const { t } = useTranslation();
  const { handleSuccess, setCloseOnEscape } = useRouteModal();
  const { mutateAsync, isPending } = useBatchInventoryItemsLocationLevels();
  const rows = useMemo(
    () => buildRows(product, locations),
    [product, locations]
  );
  const initial = useRef(rows);
  const form = useForm({ defaultValues: { rows } });
  const columns = useColumns({ stockLocations: locations });
  const handleSubmit = form.handleSubmit(async (values) => {
    const payload = {
      create: [],
      update: [],
      delete: [],
      force: true
    };
    values.rows.forEach((row, index) => {
      const itemId = row.inventory_item_id;
      if (!itemId) return;
      const initialRow = initial.current[index];
      for (const [locationId, level] of Object.entries(row.inventory)) {
        const prior = initialRow?.inventory?.[locationId];
        if (level.id) {
          if (prior?.checked && !level.checked) {
            payload.delete.push(level.id);
          } else {
            const next = castNumber(level.quantity);
            if (next !== castNumber(prior?.quantity)) {
              payload.update.push({
                inventory_item_id: itemId,
                location_id: locationId,
                stocked_quantity: next
              });
            }
          }
        } else if (level.checked && level.quantity !== "") {
          payload.create.push({
            inventory_item_id: itemId,
            location_id: locationId,
            stocked_quantity: castNumber(level.quantity)
          });
        }
      }
    });
    await mutateAsync(payload, {
      onSuccess: async () => {
        await queryClient.invalidateQueries({
          queryKey: offerQueryKeys.lists()
        });
        await queryClient.invalidateQueries({
          queryKey: productsQueryKeys.detail(productId)
        });
        toast.success(t("offers.inventory.successToast"));
        handleSuccess();
      },
      onError: (error) => toast.error(error.message)
    });
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      "data-testid": "offer-edit-stock-form",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex-1 overflow-hidden p-0", children: /* @__PURE__ */ jsx(
          DataGrid,
          {
            columns,
            data: rows,
            state: form,
            onEditingChange: (editing) => setCloseOnEscape(!editing)
          }
        ) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};
var OfferEditStockPage = () => {
  const { id } = useParams();
  const { t } = useTranslation();
  const { product, isPending, isError, error } = useProduct(id, {
    fields: OFFER_PRODUCT_DETAIL_FIELDS
  });
  const { stock_locations, isPending: isLocationsPending } = useStockLocations({
    limit: 100
  });
  if (isError) throw error;
  const ready = !isPending && !!product && !isLocationsPending && !!stock_locations;
  return /* @__PURE__ */ jsxs(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("offers.inventory.header") }) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("offers.inventory.description") }) }),
    ready && /* @__PURE__ */ jsx(
      EditStockGrid,
      {
        product,
        productId: id,
        locations: stock_locations
      }
    )
  ] });
};
var Component = OfferEditStockPage;
export {
  Component,
  OfferEditStockPage
};
