import { jsxs as C, jsx as t } from "react/jsx-runtime";
import { useMemo as f, useCallback as ze, useRef as oe, useEffect as Ke } from "react";
import { useReactTable as Le, getPaginationRowModel as Oe, getFilteredRowModel as He, getSortedRowModel as _e, getCoreRowModel as Ne } from "@tanstack/react-table";
import { COLUMN_MIN_SIZE as Ge, DEFAULT_PAGE_SIZE as Ue, DEFAULT_ROW_HEIGHT as Be, DEFAULT_TABLE_SIZE as Ze } from "./constants/tableDefaults.js";
import je from "./hooks/useDataTableResizing.js";
import Ve from "./hooks/useTableData.js";
import We from "./hooks/useTableState.js";
import Pe from "./hooks/useTableColumns.js";
import qe from "./hooks/useTableFilterInput.js";
import Je from "./hooks/useAutoTableHeight.js";
import { tableSizes as Qe } from "./types/TableSize.js";
import I from "../box/Box.js";
import Xe from "./components/data-table-global-search/DataTableGlobalSearch.js";
import Ye from "./components/data-table-date-picker/DataTableDatePicker.js";
import $e from "./components/data-table-fillter-input/DataTableFilterInput.js";
import { FilterInputMode as se } from "./types/FilterInputMode.js";
import ke from "./components/data-table-more-filter/DataTableMoreFilter.js";
import we from "../button/Button.js";
import Se from "./components/data-table-save-filter/DataTableSaveFilter.js";
import en from "./components/data-table-column-selector/DataTableColumnSelector.js";
import { DataTableStaticProvider as nn } from "./context/DataTableStaticContext.js";
import an from "../app-header/AppHeader.js";
import { DataTableDynamicProvider as tn } from "./context/DataTableDynamicContext.js";
import on from "./components/data-table-container/DataTableContainer.js";
import sn from "./components/data-table-header/DataTableHeader.js";
import ln from "./components/data-table-body/DataTableBody.js";
import mn from "./components/data-table-empty/DataTableEmpty.js";
import un from "./components/data-table-selected-action/DataTableSelectedAction.js";
import { c as le } from "../../index-BtlgVD4m.js";
import "./enums/ColumnActionEnum.js";
import "./types/FilterValueType.js";
const jn = ({
  dataSource: me,
  columns: g,
  emptyContent: ue,
  toolbar: R,
  title: c,
  description: M,
  hasColumnSeparator: _,
  size: F = Ze,
  onRowClick: N,
  onRowDoubleClick: G,
  onHeaderClick: U,
  rowsSelection: n,
  isLoading: de,
  onScrollEnd: pe,
  columnResize: T,
  columnAction: x,
  columnSelector: s,
  globalSearch: m,
  rowAction: r,
  tableHeight: y,
  filter: e,
  rowKey: i,
  cellEdit: B,
  datePicker: u = { mode: "range", enabled: !1 },
  draggable: E,
  headerStyle: d
}) => {
  const A = f(() => {
    if (R)
      return R;
    if (!(!c && !M))
      return {
        title: c ?? "",
        subtitle: M
      };
  }, [M, c, R]), { memoizedData: l = [], emptyStateContent: ge } = Ve(me, ue), { selectedRow: re, selectedRows: Z, sorting: j, setSorting: V, handleRowSelectionChange: ie } = We(l, i, n), { memoizedColumns: W, columnInitialSize: be, selectedColumns: P, columnOrder: z, setColumnOrder: h, handleSelectedColumns: Ce } = Pe(
    g,
    n,
    r,
    s,
    E
  ), { memoizedFilterCondition: o, handleFilterInputChange: K, handleClearAllFilters: Te } = qe(e), he = ze(
    (a) => {
      var ae;
      const p = new Set(a.map(String)), b = ((e == null ? void 0 : e.selectedFilterableColumnKeys) ?? []).filter((H) => !p.has(String(H)));
      if (b.length > 0 && o) {
        const H = b.reduce(
          (te, Ae) => (te[Ae] = null, te),
          {}
        );
        K(H);
      }
      (ae = e == null ? void 0 : e.onSelectedFilterableColumnKeysChange) == null || ae.call(e, a);
    },
    [e, o, K]
  ), L = oe(null), q = oe(null), J = y === "auto", Q = Je({ outerRef: q, tableContainerRef: L, enabled: J }), O = Qe[F] || Be, X = f(() => ({
    header: { backgroundColor: d == null ? void 0 : d.backgroundColor },
    headerText: { color: d == null ? void 0 : d.color }
  }), [d]), De = Le({
    data: l,
    columns: W,
    enableRowSelection: (n == null ? void 0 : n.enabled) ?? !1,
    enableSorting: !0,
    enableColumnResizing: (T == null ? void 0 : T.enabled) ?? !1,
    defaultColumn: {
      minSize: Ge
      // Set minimum width for all columns
    },
    state: {
      rowSelection: re,
      columnOrder: z
    },
    initialState: {
      pagination: {
        pageSize: Math.max((l == null ? void 0 : l.length) || 0, Ue)
      }
    },
    onColumnOrderChange: h,
    getCoreRowModel: Ne(),
    getSortedRowModel: _e(),
    getFilteredRowModel: He(),
    getPaginationRowModel: Oe(),
    onRowSelectionChange: ie,
    getRowId: (a, p) => String(i ? a[i] : p)
  }), { setColumnSizing: ve, setPageSize: Y, getHeaderGroups: fe, getRowModel: Ie, getAllLeafColumns: Re, getState: ce } = De, {
    columnSizingInfo: { isResizingColumn: $, deltaOffset: k },
    columnSizing: D
  } = ce(), Me = fe(), Fe = Re(), { rows: v } = Ie(), { handleAutoResize: w, handleAutoResizeAll: S } = je({
    setColumnSizing: ve,
    columnResize: T,
    columnAction: x,
    columnSizingState: D,
    columnInitialSize: be,
    allLeafColumns: Fe,
    rows: v
  });
  Ke(() => {
    l.length && Y(l.length);
  }, [l.length, Y]);
  const xe = f(
    () => ({
      hasColumnSeparator: _,
      size: F,
      rowHeight: O,
      rowsSelection: n,
      columns: g,
      rowKey: i,
      tableHeight: y,
      autoHeight: Q,
      columnAction: x,
      cellEdit: B,
      columnOrder: z,
      draggable: E,
      onHeaderClick: U,
      onRowClick: N,
      onRowDoubleClick: G,
      setColumnOrder: h,
      styles: X
    }),
    [
      _,
      F,
      O,
      n,
      g,
      i,
      y,
      Q,
      x,
      B,
      z,
      E,
      U,
      N,
      G,
      h,
      X
    ]
  ), ye = f(
    () => ({ sorting: j, setSorting: V, handleAutoResize: w, handleAutoResizeAll: S, columnSizingState: D }),
    [j, V, w, S, D]
  ), ee = (n == null ? void 0 : n.enabled) && Z.length > 0 && ((n == null ? void 0 : n.menuItems) || []).length > 0;
  n != null && n.enabled && !n.menuItems.length && console.warn(
    "DataTable: Rows selection is enabled but no menu items are provided. Please provide at least one menu item. E.g: rowsSelection={{ enabled: true, menuItems: [{ label: 'Delete', icon: 'Trash2', onClick: (record) => console.log('Delete', record) }]}"
  ), r != null && r.enabled && !r.menuItems.length && console.warn(
    "DataTable: Row action is enabled but no menu items are provided. Please provide at least one menu item. E.g: rowAction={{ enabled: true, menuItems: [{ label: 'Delete', type: DropdownItem.Default, icon: 'Trash2', onClick: (record) => console.log('Delete', record) }]}"
  );
  const ne = (m == null ? void 0 : m.enabled) || (s == null ? void 0 : s.enabled) || (e == null ? void 0 : e.enabled) || (u == null ? void 0 : u.enabled), Ee = ne ? /* @__PURE__ */ C(
    I,
    {
      className: le("flex flex-wrap items-center gap-[var(--spacing-3)] relative", ee && "opacity-20 pointer-events-none"),
      children: [
        (m == null ? void 0 : m.enabled) && /* @__PURE__ */ t(Xe, { ...m }),
        (u == null ? void 0 : u.enabled) && /* @__PURE__ */ t(Ye, { ...u }),
        (e == null ? void 0 : e.enabled) && e.filterableColumns.length > 0 && // When selectedFilterableColumnKeys is controlled (onSelectedFilterableColumnKeysChange provided),
        // only render filter inputs for the currently selected column keys.
        // Otherwise render all filterable columns (backward-compatible behaviour).
        e.filterableColumns.filter((a) => e.onSelectedFilterableColumnKeysChange ? (e.selectedFilterableColumnKeys ?? []).includes(a.columnKey) : !0).map((a) => {
          var p, b;
          return /* @__PURE__ */ t(
            $e,
            {
              onChange: K,
              value: (p = o == null ? void 0 : o[a.columnKey]) == null ? void 0 : p.value,
              operator: (b = o == null ? void 0 : o[a.columnKey]) == null ? void 0 : b.operator,
              options: "options" in a ? a.options ?? [] : [],
              mode: "mode" in a ? a.mode ?? se.MULTI : se.MULTI,
              columnKey: a.columnKey,
              valueType: a.valueType
            },
            a.columnKey.toString()
          );
        }),
        (e == null ? void 0 : e.enabled) && e.filterableColumns.length > 0 && e.onSelectedFilterableColumnKeysChange && /* @__PURE__ */ t(
          ke,
          {
            filterableColumns: e.filterableColumns,
            selectedKeys: e.selectedFilterableColumnKeys ?? [],
            onSelectionChange: he
          }
        ),
        (e == null ? void 0 : e.enabled) && o && Object.keys(o).length > 0 && /* @__PURE__ */ t(we, { variant: "ghost", label: "Zurücksetzen", onClick: Te }),
        (e == null ? void 0 : e.enabled) && e.hasFilterSaving && /* @__PURE__ */ t(Se, { conditions: o, presets: e.presets, onSavePreset: e.onSavePreset }),
        (s == null ? void 0 : s.enabled) && /* @__PURE__ */ t(en, { ...s, onChange: Ce })
      ]
    }
  ) : null;
  return /* @__PURE__ */ t(nn, { value: xe, children: /* @__PURE__ */ C(I, { ref: q, className: le("flex flex-col gap-[var(--spacing-6)] w-full", J && "h-full min-h-0 overflow-hidden"), children: [
    (A || ne) && /* @__PURE__ */ C(I, { className: "flex flex-col gap-[var(--spacing-6)]", children: [
      A && /* @__PURE__ */ t(an, { ...A }),
      Ee
    ] }),
    /* @__PURE__ */ C(I, { className: "relative", children: [
      /* @__PURE__ */ t(tn, { value: ye, children: /* @__PURE__ */ C(
        on,
        {
          containerRef: L,
          onScrollEnd: pe,
          isLoading: de,
          rowLength: v.length,
          rowHeight: O,
          setColumnOrder: h,
          children: [
            /* @__PURE__ */ t(
              sn,
              {
                headerGroups: Me,
                selectedColumns: P || g,
                columnSizingId: $,
                columnSizingDeltaOffset: k
              }
            ),
            v.length > 0 ? /* @__PURE__ */ t(
              ln,
              {
                tableContainerRef: L,
                rows: v,
                columnSizingId: $,
                columnSizingDeltaOffset: k,
                columnSize: D,
                selectedColumns: P || g
              }
            ) : /* @__PURE__ */ t(mn, { colSpan: W.length, emptyContent: ge })
          ]
        }
      ) }),
      ee && /* @__PURE__ */ t(
        un,
        {
          selectedRows: Z,
          rowActions: (n == null ? void 0 : n.menuItems) || [],
          overlayClassName: n == null ? void 0 : n.overlayClassName
        }
      )
    ] })
  ] }) });
};
export {
  jn as default
};
//# sourceMappingURL=DataTable.js.map
