import {
  RouteDrawer
} from "./chunk-WVA4O7QS.mjs";
import {
  useRouteModal
} from "./chunk-D6UW7URG.mjs";
import {
  InfiniteList
} from "./chunk-YCDDT44O.mjs";
import "./chunk-OBQI23QM.mjs";
import {
  useStockLocations
} from "./chunk-CDORR33H.mjs";
import {
  useBatchInventoryItemLocationLevels,
  useInventoryItem
} from "./chunk-35NDWZ4I.mjs";
import "./chunk-7AXHHXCX.mjs";
import "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import {
  sdk
} from "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

// src/routes/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/routes/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/routes/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 /* @__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),
      children: [
        /* @__PURE__ */ jsx("div", { className: "h-5 w-5", children: /* @__PURE__ */ jsx(
          Checkbox,
          {
            onClick: (e) => {
              e.stopPropagation();
              onSelect(!selected);
            },
            checked: selected
          }
        ) }),
        /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col", children: [
          /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", children: location.name }),
          /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "text-ui-fg-subtle", children: [
            location.address?.address_1,
            location.address?.city,
            location.address?.country_code
          ].filter((el) => !!el).join(", ") })
        ] })
      ]
    }
  );
};

// src/routes/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(
    Input,
    {
      type: "text",
      placeholder: placeholder || t("general.search"),
      value: searchValue,
      onChange: (e) => setSearchValue(e.target.value),
      className: "w-full"
    }
  );
};

// src/routes/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", children: [
    /* @__PURE__ */ jsxs2(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-4 overflow-auto", children: [
      /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-2 divide-y rounded-lg border", children: [
        /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-2 divide-x", children: [
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", children: t("fields.title") }),
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", children: item.title ?? "-" })
        ] }),
        /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-2 divide-x", children: [
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", children: t("fields.sku") }),
          /* @__PURE__ */ jsx3(Text2, { className: "px-2 py-1.5", size: "small", leading: "compact", children: item.sku })
        ] })
      ] }),
      /* @__PURE__ */ jsxs2("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx3(Text2, { size: "small", weight: "plus", leading: "compact", children: t("locations.domain") }),
        /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle flex w-full justify-between", children: [
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", children: t("locations.selectLocations") }),
          /* @__PURE__ */ jsxs2(Text2, { size: "small", leading: "compact", children: [
            "(",
            t("general.countOfTotalSelected", {
              count: selectedLocationIds.size,
              total: count
            }),
            ")"
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx3(
        LocationSearchInput,
        {
          onSearchChange: setSearchQuery,
          placeholder: t("general.search")
        }
      ),
      /* @__PURE__ */ jsx3("div", { className: "min-h-0 flex-1", children: /* @__PURE__ */ jsx3(
        InfiniteList,
        {
          queryKey: ["stock-locations", searchQuery],
          queryFn: async (params) => {
            const response = await sdk.admin.stockLocation.list({
              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", children: /* @__PURE__ */ jsx3(Text2, { size: "small", className: "text-ui-fg-subtle", children: searchQuery ? t("locations.noLocationsFound") : t("locations.noLocationsFound") }) }),
          pageSize: 20
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx3(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx3(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx3(Button, { onClick: handleSubmit, size: "small", isLoading: false, children: t("actions.save") })
    ] }) })
  ] });
};

// src/routes/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, { children: [
    /* @__PURE__ */ jsx4(RouteDrawer.Header, { children: /* @__PURE__ */ jsx4(Heading, { children: t("inventory.manageLocations") }) }),
    ready && /* @__PURE__ */ jsx4(ManageLocationsForm, { item: inventoryItem, locations: stock_locations })
  ] });
};
export {
  ManageLocationsDrawer as Component
};
