import {
  InfiniteList
} from "./chunk-WMA3WTCM.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import "./chunk-3QSRE5LS.js";
import {
  useStockLocations
} from "./chunk-EPHVGD5Z.js";
import {
  useBatchInventoryItemLocationLevels,
  useInventoryItem
} from "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

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

// src/pages/inventory/inventory-detail/components/manage-locations/components/manage-locations-form.tsx
import { Button, Text as Text2, toast } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useMemo, useState as useState2 } from "react";

// src/pages/inventory/inventory-detail/components/manage-locations/components/location-item.tsx
import { Checkbox, Text, clx } from "@medusajs/ui";
import { jsx, jsxs } from "react/jsx-runtime";
var LocationItem = ({
  selected,
  onSelect,
  location
}) => {
  return (
    // oxlint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: clx(
          "flex w-full cursor-pointer gap-x-2 rounded-lg border px-2 py-2",
          {
            "border-ui-border-interactive ": selected
          }
        ),
        onClick: () => onSelect(!selected),
        "data-testid": `inventory-manage-locations-form-location-item-${location.id}`,
        children: [
          /* @__PURE__ */ jsx("div", { className: "h-5 w-5", "data-testid": `inventory-manage-locations-form-location-item-${location.id}-checkbox-container`, children: /* @__PURE__ */ jsx(
            Checkbox,
            {
              onClick: (e) => {
                e.stopPropagation();
                onSelect(!selected);
              },
              checked: selected,
              "data-testid": `inventory-manage-locations-form-location-item-${location.id}-checkbox`
            }
          ) }),
          /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col", "data-testid": `inventory-manage-locations-form-location-item-${location.id}-details`, children: [
            /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", "data-testid": `inventory-manage-locations-form-location-item-${location.id}-name`, children: location.name }),
            /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "text-ui-fg-subtle", "data-testid": `inventory-manage-locations-form-location-item-${location.id}-address`, children: [
              location.address?.address_1,
              location.address?.city,
              location.address?.country_code
            ].filter((el) => !!el).join(", ") })
          ] })
        ]
      }
    )
  );
};

// src/pages/inventory/inventory-detail/components/manage-locations/components/location-search-input.tsx
import { Input } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useState, useEffect } from "react";
import { jsx as jsx2 } from "react/jsx-runtime";
var LocationSearchInput = ({
  onSearchChange,
  placeholder
}) => {
  const { t } = useTranslation();
  const [searchValue, setSearchValue] = useState("");
  useEffect(() => {
    const timer = setTimeout(() => {
      onSearchChange(searchValue);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchValue, onSearchChange]);
  return /* @__PURE__ */ jsx2("div", { "data-testid": "inventory-manage-locations-form-search-input-wrapper", children: /* @__PURE__ */ jsx2(
    Input,
    {
      type: "text",
      placeholder: placeholder || t("general.search"),
      value: searchValue,
      onChange: (e) => setSearchValue(e.target.value),
      className: "w-full",
      "data-testid": "inventory-manage-locations-form-search-input"
    }
  ) });
};

// src/pages/inventory/inventory-detail/components/manage-locations/components/manage-locations-form.tsx
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var ManageLocationsForm = ({
  item
}) => {
  const existingLocationLevels = useMemo(
    () => new Set(item.location_levels?.map((l) => l.location_id) ?? []),
    [item.location_levels]
  );
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const [searchQuery, setSearchQuery] = useState2("");
  const [selectedLocationIds, setSelectedLocationIds] = useState2(
    existingLocationLevels
  );
  const { count } = useStockLocations({ limit: 1, fields: "id" });
  const handleLocationSelect = (locationId, selected) => {
    setSelectedLocationIds((prev) => {
      const newSet = new Set(prev);
      if (selected) {
        newSet.add(locationId);
      } else {
        newSet.delete(locationId);
      }
      return newSet;
    });
  };
  const { mutateAsync } = useBatchInventoryItemLocationLevels(item.id);
  const handleSubmit = async () => {
    const toCreate = Array.from(selectedLocationIds).filter(
      (id) => !existingLocationLevels.has(id)
    );
    const toDeleteLocations = Array.from(existingLocationLevels).filter(
      (id) => !selectedLocationIds.has(id)
    );
    const toDelete = toDeleteLocations.map((id) => item.location_levels?.find((l) => l.location_id === id)?.id).filter(Boolean);
    await mutateAsync(
      {
        create: toCreate.map((location_id) => ({
          location_id
        })),
        delete: toDelete
      },
      {
        onSuccess: () => {
          toast.success(t("inventory.toast.updateLocations"));
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsxs2("div", { className: "flex flex-1 flex-col overflow-hidden", "data-testid": "inventory-manage-locations-form", children: [
    /* @__PURE__ */ jsxs2(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-4 overflow-auto", "data-testid": "inventory-manage-locations-form-body", children: [
      /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-2 divide-y rounded-lg border", "data-testid": "inventory-manage-locations-form-item-info", children: [
        /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-2 divide-x", "data-testid": "inventory-manage-locations-form-item-title-row", children: [
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-item-title-label", children: t("fields.title") }),
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-item-title-value", children: item.title ?? "-" })
        ] }),
        /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-2 divide-x", "data-testid": "inventory-manage-locations-form-item-sku-row", children: [
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-item-sku-label", children: t("fields.sku") }),
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-item-sku-value", children: item.sku })
        ] })
      ] }),
      /* @__PURE__ */ jsxs2("div", { className: "flex flex-col", "data-testid": "inventory-manage-locations-form-header", children: [
        /* @__PURE__ */ jsx3(Text2, { size: "small", weight: "plus", leading: "compact", "data-testid": "inventory-manage-locations-form-header-title", children: t("locations.domain") }),
        /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle flex w-full justify-between", "data-testid": "inventory-manage-locations-form-header-info", children: [
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-header-label", children: t("locations.selectLocations") }),
          /* @__PURE__ */ jsxs2(Text2, { size: "small", leading: "compact", "data-testid": "inventory-manage-locations-form-header-count", children: [
            "(",
            t("general.countOfTotalSelected", {
              count: selectedLocationIds.size,
              total: count
            }),
            ")"
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx3("div", { "data-testid": "inventory-manage-locations-form-search-wrapper", children: /* @__PURE__ */ jsx3(
        LocationSearchInput,
        {
          onSearchChange: setSearchQuery,
          placeholder: t("general.search")
        }
      ) }),
      /* @__PURE__ */ jsx3("div", { className: "min-h-0 flex-1", "data-testid": "inventory-manage-locations-form-locations-list", children: /* @__PURE__ */ jsx3(
        InfiniteList,
        {
          queryKey: ["stock-locations", searchQuery],
          queryFn: async (params) => {
            const response = await sdk.admin.stockLocations.query({
              limit: params.limit,
              offset: params.offset,
              ...searchQuery && { q: searchQuery }
            });
            return response;
          },
          responseKey: "stock_locations",
          renderItem: (location) => /* @__PURE__ */ jsx3(
            LocationItem,
            {
              selected: selectedLocationIds.has(location.id),
              location,
              onSelect: (selected) => handleLocationSelect(location.id, selected)
            }
          ),
          renderEmpty: () => /* @__PURE__ */ jsx3("div", { className: "flex items-center justify-center py-8", "data-testid": "inventory-manage-locations-form-empty-state", children: /* @__PURE__ */ jsx3(Text2, { size: "small", className: "text-ui-fg-subtle", "data-testid": "inventory-manage-locations-form-empty-state-text", children: searchQuery ? t("locations.noLocationsFound") : t("locations.noLocationsFound") }) }),
          pageSize: 20
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx3(RouteDrawer.Footer, { "data-testid": "inventory-manage-locations-form-footer", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", "data-testid": "inventory-manage-locations-form-footer-actions", children: [
      /* @__PURE__ */ jsx3(RouteDrawer.Close, { asChild: true, "data-testid": "inventory-manage-locations-form-cancel-button-wrapper", children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", "data-testid": "inventory-manage-locations-form-cancel-button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx3(Button, { onClick: handleSubmit, size: "small", isLoading: false, "data-testid": "inventory-manage-locations-form-save-button", children: t("actions.save") })
    ] }) })
  ] });
};

// src/pages/inventory/inventory-detail/components/manage-locations/manage-locations-drawer.tsx
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
var ManageLocationsDrawer = () => {
  const { id } = useParams();
  const { t } = useTranslation3();
  const {
    inventory_item: inventoryItem,
    isPending: isLoading,
    isError,
    error
  } = useInventoryItem(id);
  const { stock_locations, isLoading: loadingLocations } = useStockLocations();
  const ready = !isLoading && !loadingLocations && inventoryItem && stock_locations;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs3(RouteDrawer, { "data-testid": "inventory-manage-locations-drawer", children: [
    /* @__PURE__ */ jsx4(RouteDrawer.Header, { "data-testid": "inventory-manage-locations-drawer-header", children: /* @__PURE__ */ jsx4(Heading, { "data-testid": "inventory-manage-locations-drawer-title", children: t("inventory.manageLocations") }) }),
    ready && /* @__PURE__ */ jsx4(ManageLocationsForm, { item: inventoryItem, locations: stock_locations })
  ] });
};
export {
  ManageLocationsDrawer as Component
};
