import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";

// src/components/data-table/data-table.tsx
import {
  DataTable as UiDataTable,
  useDataTable,
  Heading,
  Text,
  Button
} from "@medusajs/ui";
import React, { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var DataTable = ({
  data = [],
  columns,
  filters,
  commands,
  action,
  actions,
  actionMenu,
  getRowId,
  rowCount = 0,
  enablePagination = true,
  enableSearch = true,
  autoFocusSearch: _autoFocusSearch = false,
  enableFilterMenu,
  rowHref,
  heading,
  headingLevel = "h1",
  subHeading,
  prefix,
  pageSize = 10,
  emptyState,
  rowSelection,
  isLoading = false,
  layout = "auto",
  enableColumnVisibility = false,
  initialColumnVisibility = {},
  onColumnVisibilityChange,
  columnOrder,
  onColumnOrderChange,
  enableViewSelector: _enableViewSelector = false,
  entity: _entity,
  currentColumns: _currentColumns,
  filterBarContent
}) => {
  const { t } = useTranslation();
  const enableFiltering = filters && filters.length > 0;
  const showFilterMenu = enableFilterMenu !== void 0 ? enableFilterMenu : enableFiltering;
  const enableCommands = commands && commands.length > 0;
  const enableSorting = columns.some((column) => column.enableSorting);
  const [columnVisibility, setColumnVisibility] = React.useState(initialColumnVisibility);
  React.useEffect(() => {
    const currentKeys = Object.keys(columnVisibility).sort();
    const newKeys = Object.keys(initialColumnVisibility).sort();
    const hasChanged = currentKeys.length !== newKeys.length || currentKeys.some((key, index) => key !== newKeys[index]) || Object.entries(initialColumnVisibility).some(
      ([key, value]) => columnVisibility[key] !== value
    );
    if (hasChanged) {
      setColumnVisibility(initialColumnVisibility);
    }
  }, [initialColumnVisibility, columnVisibility]);
  const handleColumnVisibilityChange = React.useCallback(
    (visibility) => {
      setColumnVisibility(visibility);
      onColumnVisibilityChange?.(visibility);
    },
    [onColumnVisibilityChange]
  );
  const filterIds = useMemo(() => filters?.map((f) => f.id) ?? [], [filters]);
  const prefixedFilterIds = filterIds.map((id) => getQueryParamKey(id, prefix));
  const { offset, order, q, ...filterParams } = useQueryParams(
    [
      ...filterIds,
      ...enableSorting ? ["order"] : [],
      ...enableSearch ? ["q"] : [],
      ...enablePagination ? ["offset"] : []
    ],
    prefix
  );
  const [_, setSearchParams] = useSearchParams();
  const search = useMemo(() => {
    return q ?? "";
  }, [q]);
  const handleSearchChange = (value) => {
    setSearchParams((prev) => {
      if (value) {
        prev.set(getQueryParamKey("q", prefix), value);
      } else {
        prev.delete(getQueryParamKey("q", prefix));
      }
      return prev;
    });
  };
  const pagination = useMemo(() => {
    return offset ? parsePaginationState(offset, pageSize) : { pageIndex: 0, pageSize };
  }, [offset, pageSize]);
  const handlePaginationChange = (value) => {
    setSearchParams((prev) => {
      if (value.pageIndex === 0) {
        prev.delete(getQueryParamKey("offset", prefix));
      } else {
        prev.set(
          getQueryParamKey("offset", prefix),
          transformPaginationState(value).toString()
        );
      }
      return prev;
    });
  };
  const filtering = useMemo(
    () => parseFilterState(filterIds, filterParams),
    [filterIds, filterParams]
  );
  const handleFilteringChange = (value) => {
    setSearchParams((prev) => {
      Array.from(prev.keys()).forEach((key) => {
        if (prefixedFilterIds.includes(key)) {
          const unprefixedKey = prefix ? key.replace(`${prefix}_`, "") : key;
          if (!(unprefixedKey in value)) {
            prev.delete(key);
          }
        }
      });
      Object.entries(value).forEach(([key, filter]) => {
        const prefixedKey = getQueryParamKey(key, prefix);
        if (filter !== void 0) {
          prev.set(prefixedKey, JSON.stringify(filter));
        } else {
          prev.delete(prefixedKey);
        }
      });
      return prev;
    });
  };
  const sorting = useMemo(() => {
    return order ? parseSortingState(order) : null;
  }, [order]);
  const handleSortingChange = (value) => {
    setSearchParams((prev) => {
      if (value) {
        const valueToStore = transformSortingState(value);
        prev.set(getQueryParamKey("order", prefix), valueToStore);
      } else {
        prev.delete(getQueryParamKey("order", prefix));
      }
      return prev;
    });
  };
  const { pagination: paginationTranslations, toolbar: toolbarTranslations } = useDataTableTranslations();
  const navigate = useNavigate();
  const onRowClick = useCallback(
    (event, row) => {
      if (!rowHref) {
        return;
      }
      const href = rowHref(row);
      const basePath = "/";
      const hrefWithBasePath = `${basePath === "/" ? "" : basePath}${href}`;
      if (event.metaKey || event.ctrlKey || event.button === 1) {
        window.open(hrefWithBasePath, "_blank", "noreferrer");
        return;
      }
      if (event.shiftKey) {
        window.open(hrefWithBasePath, void 0, "noreferrer");
        return;
      }
      navigate(href);
    },
    [navigate, rowHref]
  );
  const instance = useDataTable({
    data,
    columns,
    filters,
    commands,
    rowCount,
    getRowId,
    onRowClick: rowHref ? onRowClick : void 0,
    pagination: enablePagination ? {
      state: pagination,
      onPaginationChange: handlePaginationChange
    } : void 0,
    filtering: enableFiltering ? {
      state: filtering,
      onFilteringChange: handleFilteringChange
    } : void 0,
    sorting: enableSorting ? {
      state: sorting,
      onSortingChange: handleSortingChange
    } : void 0,
    search: enableSearch ? {
      state: search,
      onSearchChange: handleSearchChange
    } : void 0,
    rowSelection,
    isLoading,
    columnVisibility: enableColumnVisibility ? {
      state: columnVisibility,
      onColumnVisibilityChange: handleColumnVisibilityChange
    } : void 0,
    columnOrder: columnOrder && onColumnOrderChange ? {
      state: columnOrder,
      onColumnOrderChange
    } : void 0
  });
  const shouldRenderHeading = heading || subHeading;
  const hasToolbarHeader = Boolean(shouldRenderHeading) || Boolean(actionMenu) || Boolean(actions && actions.length > 0) || Boolean(action);
  return /* @__PURE__ */ jsxs(
    UiDataTable,
    {
      instance,
      className: layout === "fill" ? "h-full [&_tr]:last-of-type:!border-b" : void 0,
      children: [
        hasToolbarHeader ? /* @__PURE__ */ jsx(
          UiDataTable.Toolbar,
          {
            className: "flex flex-col items-start justify-between gap-2 md:flex-row md:items-center",
            translations: toolbarTranslations,
            filterBarContent,
            children: /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center justify-between gap-2", children: [
              /* @__PURE__ */ jsx("div", { className: "flex items-center gap-x-4", children: shouldRenderHeading && /* @__PURE__ */ jsxs("div", { children: [
                heading && /* @__PURE__ */ jsx(Heading, { level: headingLevel, children: heading }),
                subHeading && /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: subHeading })
              ] }) }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
                showFilterMenu && /* @__PURE__ */ jsx(UiDataTable.FilterMenu, {}),
                enableSorting && /* @__PURE__ */ jsx(UiDataTable.SortingMenu, {}),
                enableSearch && /* @__PURE__ */ jsx("div", { className: "w-full md:w-auto", children: /* @__PURE__ */ jsx(
                  UiDataTable.Search,
                  {
                    placeholder: t("filters.searchLabel")
                  }
                ) }),
                actionMenu && /* @__PURE__ */ jsx(ActionMenu, { variant: "primary", ...actionMenu }),
                actions && actions.length > 0 && /* @__PURE__ */ jsx(DataTableActions, { actions }),
                !actions && action && /* @__PURE__ */ jsx(DataTableAction, { ...action })
              ] })
            ] })
          }
        ) : /* @__PURE__ */ jsxs(
          UiDataTable.FilterBar,
          {
            alwaysShow: true,
            clearAllFiltersLabel: toolbarTranslations.clearAll,
            sortingTooltip: toolbarTranslations.sort,
            columnsTooltip: toolbarTranslations.columns,
            children: [
              enableSearch && /* @__PURE__ */ jsx(UiDataTable.Search, { placeholder: t("filters.searchLabel") }),
              filterBarContent
            ]
          }
        ),
        /* @__PURE__ */ jsx(UiDataTable.Table, { emptyState }),
        enablePagination && /* @__PURE__ */ jsx(UiDataTable.Pagination, { translations: paginationTranslations }),
        enableCommands && /* @__PURE__ */ jsx(
          UiDataTable.CommandBar,
          {
            selectedLabel: (count) => `${count} selected`
          }
        )
      ]
    }
  );
};
function transformSortingState(value) {
  return value.desc ? `-${value.id}` : value.id;
}
function parseSortingState(value) {
  return value.startsWith("-") ? { id: value.slice(1), desc: true } : { id: value, desc: false };
}
function transformPaginationState(value) {
  return value.pageIndex * value.pageSize;
}
function parsePaginationState(value, pageSize) {
  const offset = parseInt(value);
  return {
    pageIndex: Math.floor(offset / pageSize),
    pageSize
  };
}
function parseFilterState(filterIds, value) {
  if (!value) {
    return {};
  }
  const filters = {};
  for (const id of filterIds) {
    const filterValue = value[id];
    if (filterValue !== void 0) {
      filters[id] = JSON.parse(filterValue);
    }
  }
  return filters;
}
function getQueryParamKey(key, prefix) {
  return prefix ? `${prefix}_${key}` : key;
}
var useDataTableTranslations = () => {
  const { t } = useTranslation();
  const paginationTranslations = {
    of: t("general.of"),
    results: t("general.results"),
    pages: t("general.pages"),
    prev: t("general.prev"),
    next: t("general.next")
  };
  const toolbarTranslations = {
    clearAll: t("actions.clearAll"),
    sort: t("filters.sortLabel"),
    columns: "Columns"
  };
  return {
    pagination: paginationTranslations,
    toolbar: toolbarTranslations
  };
};
var DataTableAction = ({
  label,
  disabled,
  ...props
}) => {
  const buttonProps = {
    size: "small",
    disabled: disabled ?? false,
    type: "button",
    variant: "secondary"
  };
  if ("to" in props) {
    return /* @__PURE__ */ jsx(Button, { ...buttonProps, asChild: true, children: /* @__PURE__ */ jsx(Link, { to: props.to, children: label }) });
  }
  return /* @__PURE__ */ jsx(Button, { ...buttonProps, onClick: props.onClick, children: label });
};
var DataTableActions = ({ actions }) => {
  return /* @__PURE__ */ jsx("div", { className: "flex items-center gap-x-2", children: actions.map((action, index) => /* @__PURE__ */ jsx(DataTableAction, { ...action }, index)) });
};

export {
  DataTable
};
