function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { forwardRef, useState, useMemo, useRef } from "react";
import { getCoreRowModel, useReactTable, getSortedRowModel, getFilteredRowModel } from "@tanstack/react-table";
import { useForkRef } from "../../hooks";
import cls from "classnames";
import { classes } from "./Table.tokens";
import { SELECT_COLUMN_ID } from "./utils";
import { HeadCell, Cell, EditableCell } from "./ui";
import { base, Table, Tr, Thead, StyledCheckbox, Tbody, ScrollableWrapper } from "./Table.styles";
export var tableRoot = function tableRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), data = _ref2.data, onChange = _ref2.onChange, columns = _ref2.columns, view = _ref2.view, size = _ref2.size, _ref_borderVariant = _ref2.borderVariant, borderVariant = _ref_borderVariant === void 0 ? 'all' : _ref_borderVariant, _ref_enableSelection = _ref2.enableSelection, enableSelection = _ref_enableSelection === void 0 ? false : _ref_enableSelection, outerSelected = _ref2.selected, outerFiltered = _ref2.filtered, outerSorted = _ref2.sorted, maxHeight = _ref2.maxHeight, _ref_stickyHeader = _ref2.stickyHeader, stickyHeader = _ref_stickyHeader === void 0 ? false : _ref_stickyHeader, onCellUpdate = _ref2.onCellUpdate, setRowProps = _ref2.setRowProps, topContent = _ref2.topContent, bottomContent = _ref2.bottomContent, loadingSlot = _ref2.loadingSlot, onScroll = _ref2.onScroll, classNames = _ref2.classNames, props = _object_without_properties(_ref2, [
            "data",
            "onChange",
            "columns",
            "view",
            "size",
            "borderVariant",
            "enableSelection",
            "selected",
            "filtered",
            "sorted",
            "maxHeight",
            "stickyHeader",
            "onCellUpdate",
            "setRowProps",
            "topContent",
            "bottomContent",
            "loadingSlot",
            "onScroll",
            "classNames"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _classNames_header, _classNames_body;
        var _useState = _sliced_to_array(useState(outerSelected || {}), 2), innerSelected = _useState[0], innerSetSelected = _useState[1];
        var _useState1 = _sliced_to_array(useState(outerFiltered || []), 2), innerFiltered = _useState1[0], setInnerFiltered = _useState1[1];
        var _useState2 = _sliced_to_array(useState(outerSorted || []), 2), innerSorted = _useState2[0], setInnerSorted = _useState2[1];
        var selected = outerSelected || innerSelected;
        var filtered = outerFiltered || innerFiltered;
        var sorted = outerSorted || innerSorted;
        var handleRowSelection = function handleRowSelection(updaterOrValue) {
            if (!outerSelected) {
                innerSetSelected(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected: typeof updaterOrValue === 'function' ? updaterOrValue(selected) : updaterOrValue,
                    filtered: filtered,
                    sorted: sorted
                });
            }
        };
        var handleSorting = function handleSorting(updaterOrValue) {
            if (!outerSorted) {
                setInnerSorted(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected: selected,
                    filtered: filtered,
                    sorted: typeof updaterOrValue === 'function' ? updaterOrValue(sorted) : updaterOrValue
                });
            }
        };
        var handleFiltering = function handleFiltering(updaterOrValue) {
            if (!outerFiltered) {
                setInnerFiltered(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected: selected,
                    filtered: typeof updaterOrValue === 'function' ? updaterOrValue(filtered) : updaterOrValue,
                    sorted: sorted
                });
            }
        };
        var tableContainerRef = useRef(null);
        var rootRef = useForkRef(tableContainerRef, ref);
        var columnsData = useMemo(function() {
            return _to_consumable_array(enableSelection ? [
                {
                    id: SELECT_COLUMN_ID,
                    header: function header(param) {
                        var table = param.table;
                        var _props__checkboxAppearance;
                        return /*#__PURE__*/ React.createElement(StyledCheckbox, {
                            checked: table.getIsSomeRowsSelected() || table.getIsAllRowsSelected(),
                            indeterminate: table.getIsSomeRowsSelected(),
                            onChange: table.getToggleAllRowsSelectedHandler(),
                            // eslint-disable-next-line no-underscore-dangle
                            appearance: (_props__checkboxAppearance = props._checkboxAppearance) !== null && _props__checkboxAppearance !== void 0 ? _props__checkboxAppearance : 'default'
                        });
                    },
                    cell: function cell(param) {
                        var row = param.row;
                        var _props__checkboxAppearance;
                        return /*#__PURE__*/ React.createElement(StyledCheckbox, {
                            checked: row.getIsSelected(),
                            indeterminate: row.getIsSomeSelected(),
                            onChange: row.getToggleSelectedHandler(),
                            // eslint-disable-next-line no-underscore-dangle
                            appearance: (_props__checkboxAppearance = props._checkboxAppearance) !== null && _props__checkboxAppearance !== void 0 ? _props__checkboxAppearance : 'default'
                        });
                    },
                    enableResizing: false
                }
            ] : []).concat(_to_consumable_array(columns.map(function(param) {
                var id = param.id, label = param.label, filters = param.filters, _param_enableSorting = param.enableSorting, enableSorting = _param_enableSorting === void 0 ? false : _param_enableSorting, _param_enableResizing = param.enableResizing, enableResizing = _param_enableResizing === void 0 ? false : _param_enableResizing, outerFilterFn = param.filterFn, columnSize = param.width, _param_enableEditing = param.enableEditing, enableEditing = _param_enableEditing === void 0 ? false : _param_enableEditing, renderCell = param.renderCell, setCellProps = param.setCellProps;
                return {
                    header: label,
                    accessorKey: id,
                    size: columnSize,
                    enableSorting: enableSorting,
                    enableResizing: enableResizing,
                    filterFn: function filterFn(row, columnId, filterArr) {
                        if ((filterArr === null || filterArr === void 0 ? void 0 : filterArr.length) !== 0 && outerFilterFn && filterArr && Array.isArray(filterArr)) {
                            return filterArr.some(function(filterValue) {
                                return outerFilterFn(filterValue, row.getValue(columnId));
                            });
                        }
                        return true;
                    },
                    meta: {
                        filters: filters,
                        enableEditing: enableEditing,
                        renderCell: renderCell,
                        setCellProps: setCellProps
                    }
                };
            })));
        }, [
            enableSelection,
            columns
        ]);
        var table = useReactTable({
            data: data,
            columns: columnsData,
            getRowId: function getRowId(row) {
                return row.id;
            },
            getCoreRowModel: getCoreRowModel(),
            getSortedRowModel: getSortedRowModel(),
            manualSorting: Boolean(outerSorted),
            manualFiltering: Boolean(outerFiltered),
            state: {
                rowSelection: selected,
                columnFilters: filtered,
                sorting: sorted
            },
            onSortingChange: handleSorting,
            getFilteredRowModel: getFilteredRowModel(),
            onColumnFiltersChange: handleFiltering,
            onRowSelectionChange: handleRowSelection,
            columnResizeMode: 'onChange',
            columnResizeDirection: 'ltr',
            manualPagination: true,
            meta: {
                updateData: function updateData(rowId, columnId, value) {
                    if (onCellUpdate) {
                        onCellUpdate(rowId, columnId, value);
                    }
                }
            }
        });
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            ref: rootRef,
            data: data,
            columns: columns,
            view: view,
            size: size,
            className: cls(props.className, classNames === null || classNames === void 0 ? void 0 : classNames.root, classes.root)
        }, props), topContent, /*#__PURE__*/ React.createElement(ScrollableWrapper, {
            className: classes.scrollableContainer,
            onScroll: onScroll,
            maxHeight: maxHeight
        }, /*#__PURE__*/ React.createElement(Table, {
            borderVariant: borderVariant,
            stickyHeader: stickyHeader,
            className: cls(classNames === null || classNames === void 0 ? void 0 : classNames.table, classes.table)
        }, /*#__PURE__*/ React.createElement(Thead, {
            view: view,
            borderVariant: borderVariant,
            stickyHeader: stickyHeader,
            className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_header = classNames.header) === null || _classNames_header === void 0 ? void 0 : _classNames_header.wrapper, classes.headerWrapper)
        }, table.getHeaderGroups().map(function(headerGroup) {
            var _classNames_header;
            return /*#__PURE__*/ React.createElement(Tr, {
                key: headerGroup.id,
                className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_header = classNames.header) === null || _classNames_header === void 0 ? void 0 : _classNames_header.row, classes.headerRow)
            }, headerGroup.headers.map(function(header) {
                var _classNames_header;
                return /*#__PURE__*/ React.createElement(HeadCell, {
                    key: header.index,
                    header: header,
                    size: size,
                    borderVariant: borderVariant,
                    outerFiltered: outerFiltered,
                    tableContainerRef: tableContainerRef,
                    className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_header = classNames.header) === null || _classNames_header === void 0 ? void 0 : _classNames_header.cell, classes.headerCell)
                });
            }));
        })), /*#__PURE__*/ React.createElement(Tbody, {
            className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_body = classNames.body) === null || _classNames_body === void 0 ? void 0 : _classNames_body.wrapper, classes.bodyWrapper)
        }, table.getRowModel().rows.map(function(row) {
            var _classNames_body;
            return /*#__PURE__*/ React.createElement(Tr, _object_spread({
                key: row.id,
                selected: row.getIsSelected(),
                className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_body = classNames.body) === null || _classNames_body === void 0 ? void 0 : _classNames_body.row, classes.bodyRow)
            }, setRowProps === null || setRowProps === void 0 ? void 0 : setRowProps(row.original)), row.getVisibleCells().map(function(cell) {
                var _cell_column_columnDef_meta_setCellProps, _cell_column_columnDef_meta, _cell_column_columnDef, _cell_column, _cell_column_columnDef_meta1, _cell_column_columnDef1, _cell_column1, _classNames_body, _classNames_body1;
                var additionalProps = (cell === null || cell === void 0 ? void 0 : (_cell_column = cell.column) === null || _cell_column === void 0 ? void 0 : (_cell_column_columnDef = _cell_column.columnDef) === null || _cell_column_columnDef === void 0 ? void 0 : (_cell_column_columnDef_meta = _cell_column_columnDef.meta) === null || _cell_column_columnDef_meta === void 0 ? void 0 : (_cell_column_columnDef_meta_setCellProps = _cell_column_columnDef_meta.setCellProps) === null || _cell_column_columnDef_meta_setCellProps === void 0 ? void 0 : _cell_column_columnDef_meta_setCellProps.call(_cell_column_columnDef_meta, cell.row.original, cell.id)) || {};
                return (cell === null || cell === void 0 ? void 0 : (_cell_column1 = cell.column) === null || _cell_column1 === void 0 ? void 0 : (_cell_column_columnDef1 = _cell_column1.columnDef) === null || _cell_column_columnDef1 === void 0 ? void 0 : (_cell_column_columnDef_meta1 = _cell_column_columnDef1.meta) === null || _cell_column_columnDef_meta1 === void 0 ? void 0 : _cell_column_columnDef_meta1.enableEditing) ? /*#__PURE__*/ React.createElement(EditableCell, {
                    key: cell.id,
                    size: size,
                    cell: cell,
                    borderVariant: borderVariant,
                    table: table,
                    selected: row.getIsSelected(),
                    view: view,
                    additionalProps: additionalProps,
                    className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_body = classNames.body) === null || _classNames_body === void 0 ? void 0 : _classNames_body.cell, classes.bodyCell)
                }) : /*#__PURE__*/ React.createElement(Cell, {
                    key: cell.id,
                    cell: cell,
                    borderVariant: borderVariant,
                    selected: row.getIsSelected(),
                    view: view,
                    additionalProps: additionalProps,
                    className: cls(classNames === null || classNames === void 0 ? void 0 : (_classNames_body1 = classNames.body) === null || _classNames_body1 === void 0 ? void 0 : _classNames_body1.cell, classes.bodyCell)
                });
            }));
        }))), loadingSlot), bottomContent);
    });
};
export var tableConfig = {
    name: 'Table',
    tag: 'div',
    layout: tableRoot,
    base: base,
    variations: {},
    defaults: {
        view: 'default',
        size: 'm'
    }
};
