import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  SingleColumnPage
} from "./chunk-YV6MK4PZ.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useStockLocations
} from "./chunk-O72AIZUN.js";
import {
  useDeleteInventoryItem,
  useInventoryItems
} from "./chunk-YAUGB4LD.js";

// src/pages/inventory/inventory-list-page.tsx
import { Children as Children2 } from "react";
import { WidgetZone } from "@mercurjs/dashboard-shared";

// src/pages/inventory/_components/inventory-list-table.tsx
import { Children } from "react";
import { Container } from "@medusajs/ui";
import { Outlet } from "react-router-dom";

// src/pages/inventory/_components/inventory-list-header.tsx
import { Button, Heading, Text } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var InventoryListHeader = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(Heading, { children: t("inventory.domain") }),
      /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", size: "small", children: t("inventory.subtitle") })
    ] }),
    /* @__PURE__ */ jsx(InventoryListCreateButton, {})
  ] });
};
var InventoryListCreateButton = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", asChild: true, children: /* @__PURE__ */ jsx(Link, { to: "create", children: t("actions.create") }) });
};

// src/pages/inventory/_components/inventory-list-data-table.tsx
import { useExtendableTable, useLinkQuery } from "@mercurjs/dashboard-shared";
import { useMemo as useMemo2, useState } from "react";
import { useTranslation as useTranslation5 } from "react-i18next";
import { useNavigate } from "react-router-dom";

// src/pages/inventory/common/constants.ts
var INVENTORY_ITEM_IDS_KEY = "inventory_item_ids";

// src/pages/inventory/_components/use-inventory-table-columns.tsx
import { Checkbox } from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/inventory/_components/inventory-actions.tsx
import { PencilSquare, Trash } from "@medusajs/icons";
import { usePrompt } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2 } from "react/jsx-runtime";
var InventoryActions = ({ item }) => {
  const { t } = useTranslation2();
  const prompt = usePrompt();
  const { mutateAsync } = useDeleteInventoryItem(item.id);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("inventory.deleteWarning"),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync();
  };
  return /* @__PURE__ */ jsx2(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx2(PencilSquare, {}),
              label: t("actions.edit"),
              to: `${item.id}/edit`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx2(Trash, {}),
              label: t("actions.delete"),
              onClick: handleDelete
            }
          ]
        }
      ]
    }
  );
};

// src/pages/inventory/_components/use-inventory-table-columns.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useInventoryTableColumns = () => {
  const { t } = useTranslation3();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      columnHelper.accessor("title", {
        header: t("fields.title"),
        cell: ({ getValue }) => {
          const title = getValue();
          if (!title) {
            return /* @__PURE__ */ jsx3(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx3("div", { className: "flex size-full items-center overflow-hidden", children: /* @__PURE__ */ jsx3("span", { className: "truncate", children: title }) });
        }
      }),
      columnHelper.accessor("sku", {
        header: t("fields.sku"),
        cell: ({ getValue }) => {
          const sku = getValue();
          if (!sku) {
            return /* @__PURE__ */ jsx3(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx3("div", { className: "flex size-full items-center overflow-hidden", children: /* @__PURE__ */ jsx3("span", { className: "truncate", children: sku }) });
        }
      }),
      columnHelper.accessor("location_levels", {
        header: t("inventory.reserved"),
        cell: ({ getValue }) => {
          const locations = getValue();
          const totalReserved = locations.reduce(
            (sum, level) => sum + level.reserved_quantity,
            0
          );
          if (Number.isNaN(totalReserved)) {
            return /* @__PURE__ */ jsx3(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx3("div", { className: "flex size-full items-center overflow-hidden", children: /* @__PURE__ */ jsx3("span", { className: "truncate", children: totalReserved }) });
        }
      }),
      columnHelper.accessor("location_levels", {
        header: t("fields.inStock"),
        cell: ({ getValue }) => {
          const locations = getValue();
          const totalAvailable = locations.reduce(
            (sum, level) => sum + level.available_quantity,
            0
          );
          if (Number.isNaN(totalAvailable)) {
            return /* @__PURE__ */ jsx3(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx3("div", { className: "flex size-full items-center overflow-hidden", children: /* @__PURE__ */ jsx3("span", { className: "truncate", children: totalAvailable }) });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => /* @__PURE__ */ jsx3(InventoryActions, { item: row.original })
      })
    ],
    [t]
  );
};

// src/pages/inventory/_components/use-inventory-table-filters.tsx
import { useTranslation as useTranslation4 } from "react-i18next";
var useInventoryTableFilters = () => {
  const { t } = useTranslation4();
  const { stock_locations } = useStockLocations({
    limit: 1e3
  });
  const filters = [];
  if (stock_locations) {
    const stockLocationFilter = {
      type: "select",
      options: stock_locations.map((s) => ({
        label: s.name,
        value: s.id
      })),
      key: "location_id",
      searchable: true,
      label: t("fields.location")
    };
    filters.push(stockLocationFilter);
  }
  filters.push({
    type: "string",
    key: "material",
    label: t("fields.material")
  });
  filters.push({
    type: "string",
    key: "sku",
    label: t("fields.sku")
  });
  filters.push({
    type: "string",
    key: "mid_code",
    label: t("fields.midCode")
  });
  filters.push({
    type: "number",
    key: "height",
    label: t("fields.height")
  });
  filters.push({
    type: "number",
    key: "width",
    label: t("fields.width")
  });
  filters.push({
    type: "number",
    key: "length",
    label: t("fields.length")
  });
  filters.push({
    type: "number",
    key: "weight",
    label: t("fields.weight")
  });
  filters.push({
    type: "select",
    options: [
      { label: t("fields.true"), value: "true" },
      { label: t("fields.false"), value: "false" }
    ],
    key: "requires_shipping",
    multiple: false,
    label: t("fields.requiresShipping")
  });
  return filters;
};

// src/pages/inventory/_components/use-inventory-table-query.tsx
var useInventoryTableQuery = ({
  pageSize = 20,
  prefix
}) => {
  const raw = useQueryParams(
    [
      "id",
      "location_id",
      "q",
      "order",
      "requires_shipping",
      "offset",
      "sku",
      "origin_country",
      "material",
      "mid_code",
      "hs_code",
      "order",
      "weight",
      "width",
      "length",
      "height"
    ],
    prefix
  );
  const {
    offset,
    weight,
    width,
    length,
    height,
    requires_shipping,
    ...params
  } = raw;
  const searchParams = {
    limit: pageSize,
    offset: offset ? parseInt(offset) : void 0,
    weight: weight ? JSON.parse(weight) : void 0,
    width: width ? JSON.parse(width) : void 0,
    length: length ? JSON.parse(length) : void 0,
    height: height ? JSON.parse(height) : void 0,
    requires_shipping: requires_shipping ? JSON.parse(requires_shipping) : void 0,
    q: params.q,
    sku: params.sku,
    order: params.order,
    mid_code: params.mid_code,
    hs_code: params.hs_code,
    material: params.material,
    location_levels: {
      location_id: params.location_id || []
    },
    id: params.id ? params.id.split(",") : void 0
  };
  return {
    searchParams,
    raw
  };
};

// src/pages/inventory/_components/inventory-list-data-table.tsx
import { keepPreviousData } from "@tanstack/react-query";
import { jsx as jsx4 } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var InventoryListDataTable = () => {
  const { t } = useTranslation5();
  const navigate = useNavigate();
  const [selection, setSelection] = useState({});
  const { raw, searchParams } = useInventoryTableQuery({
    pageSize: PAGE_SIZE
  });
  const {
    inventory_items,
    count,
    isPending: isLoading,
    isError,
    error
  } = useInventoryItems(
    {
      ...searchParams,
      ...useLinkQuery("inventory_item")
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const baseFilters = useInventoryTableFilters();
  const baseColumns = useInventoryTableColumns();
  const { columns, filters: extFilters } = useExtendableTable({
    model: "inventory_item",
    columns: baseColumns
  });
  const filters = useMemo2(
    () => [...baseFilters, ...extFilters],
    [baseFilters, extFilters]
  );
  const { table } = useDataTable({
    data: inventory_items ?? [],
    columns,
    count,
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enableRowSelection: true,
    rowSelection: {
      state: selection,
      updater: setSelection
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx4(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count,
      isLoading,
      pagination: true,
      search: true,
      filters,
      queryObject: raw,
      orderBy: [
        { key: "title", label: t("fields.title") },
        { key: "sku", label: t("fields.sku") },
        { key: "stocked_quantity", label: t("fields.inStock") },
        { key: "reserved_quantity", label: t("inventory.reserved") }
      ],
      navigateTo: (row) => `${row.id}`,
      commands: [
        {
          action: async (selection2) => {
            navigate(
              `stock?${INVENTORY_ITEM_IDS_KEY}=${Object.keys(selection2).join(
                ","
              )}`
            );
          },
          label: t("inventory.stock.action"),
          shortcut: "i"
        }
      ]
    }
  );
};

// src/pages/inventory/_components/inventory-list-table.tsx
import { Fragment, jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
var InventoryListTable = ({ children }) => {
  return /* @__PURE__ */ jsxs2(Container, { className: "divide-y p-0", children: [
    Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs2(Fragment, { children: [
      /* @__PURE__ */ jsx5(InventoryListHeader, {}),
      /* @__PURE__ */ jsx5(InventoryListDataTable, {})
    ] }),
    /* @__PURE__ */ jsx5(Outlet, {})
  ] });
};

// src/pages/inventory/inventory-list-page.tsx
import { jsx as jsx6 } from "react/jsx-runtime";
var Root = ({ children }) => {
  return /* @__PURE__ */ jsx6(SingleColumnPage, { children: /* @__PURE__ */ jsx6(WidgetZone, { id: "inventory.list", children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx6(InventoryListTable, {}) }) });
};
var InventoryListPage = Object.assign(Root, {
  Table: InventoryListTable,
  Header: InventoryListHeader,
  HeaderCreateButton: InventoryListCreateButton,
  DataTable: InventoryListDataTable
});

export {
  InventoryListPage
};
