"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get tableConfig () {
        return tableConfig;
    },
    get tableRoot () {
        return tableRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _reacttable = require("@tanstack/react-table");
const _hooks = require("../../hooks");
const _classnames = /*#__PURE__*/ _interop_require_default(require("classnames"));
const _Tabletokens = require("./Table.tokens");
const _utils = require("./utils");
const _ui = require("./ui");
const _Tablestyles = require("./Table.styles");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const tableRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ data, onChange, columns, view, size, borderVariant = 'all', enableSelection = false, selected: outerSelected, filtered: outerFiltered, sorted: outerSorted, maxHeight, stickyHeader = false, onCellUpdate, setRowProps, topContent, bottomContent, loadingSlot, onScroll, classNames, ...props }, ref)=>{
        const [innerSelected, innerSetSelected] = (0, _react.useState)(outerSelected || {});
        const [innerFiltered, setInnerFiltered] = (0, _react.useState)(outerFiltered || []);
        const [innerSorted, setInnerSorted] = (0, _react.useState)(outerSorted || []);
        const selected = outerSelected || innerSelected;
        const filtered = outerFiltered || innerFiltered;
        const sorted = outerSorted || innerSorted;
        const handleRowSelection = (updaterOrValue)=>{
            if (!outerSelected) {
                innerSetSelected(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected: typeof updaterOrValue === 'function' ? updaterOrValue(selected) : updaterOrValue,
                    filtered,
                    sorted
                });
            }
        };
        const handleSorting = (updaterOrValue)=>{
            if (!outerSorted) {
                setInnerSorted(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected,
                    filtered,
                    sorted: typeof updaterOrValue === 'function' ? updaterOrValue(sorted) : updaterOrValue
                });
            }
        };
        const handleFiltering = (updaterOrValue)=>{
            if (!outerFiltered) {
                setInnerFiltered(updaterOrValue);
            }
            if (onChange) {
                onChange({
                    selected,
                    filtered: typeof updaterOrValue === 'function' ? updaterOrValue(filtered) : updaterOrValue,
                    sorted
                });
            }
        };
        const tableContainerRef = (0, _react.useRef)(null);
        const rootRef = (0, _hooks.useForkRef)(tableContainerRef, ref);
        const columnsData = (0, _react.useMemo)(()=>[
                ...enableSelection ? [
                    {
                        id: _utils.SELECT_COLUMN_ID,
                        header: ({ table })=>/*#__PURE__*/ _react.default.createElement(_Tablestyles.StyledCheckbox, {
                                checked: table.getIsSomeRowsSelected() || table.getIsAllRowsSelected(),
                                indeterminate: table.getIsSomeRowsSelected(),
                                onChange: table.getToggleAllRowsSelectedHandler(),
                                // eslint-disable-next-line no-underscore-dangle
                                appearance: props._checkboxAppearance ?? 'default'
                            }),
                        cell: ({ row })=>/*#__PURE__*/ _react.default.createElement(_Tablestyles.StyledCheckbox, {
                                checked: row.getIsSelected(),
                                indeterminate: row.getIsSomeSelected(),
                                onChange: row.getToggleSelectedHandler(),
                                // eslint-disable-next-line no-underscore-dangle
                                appearance: props._checkboxAppearance ?? 'default'
                            }),
                        enableResizing: false
                    }
                ] : [],
                ...columns.map(({ id, label, filters, enableSorting = false, enableResizing = false, filterFn: outerFilterFn, width: columnSize, enableEditing = false, renderCell, setCellProps })=>({
                        header: label,
                        accessorKey: id,
                        size: columnSize,
                        enableSorting,
                        enableResizing,
                        filterFn: (row, columnId, filterArr)=>{
                            if (filterArr?.length !== 0 && outerFilterFn && filterArr && Array.isArray(filterArr)) {
                                return filterArr.some((filterValue)=>outerFilterFn(filterValue, row.getValue(columnId)));
                            }
                            return true;
                        },
                        meta: {
                            filters,
                            enableEditing,
                            renderCell,
                            setCellProps
                        }
                    }))
            ], [
            enableSelection,
            columns
        ]);
        const table = (0, _reacttable.useReactTable)({
            data,
            columns: columnsData,
            getRowId: (row)=>row.id,
            getCoreRowModel: (0, _reacttable.getCoreRowModel)(),
            getSortedRowModel: (0, _reacttable.getSortedRowModel)(),
            manualSorting: Boolean(outerSorted),
            manualFiltering: Boolean(outerFiltered),
            state: {
                rowSelection: selected,
                columnFilters: filtered,
                sorting: sorted
            },
            onSortingChange: handleSorting,
            getFilteredRowModel: (0, _reacttable.getFilteredRowModel)(),
            onColumnFiltersChange: handleFiltering,
            onRowSelectionChange: handleRowSelection,
            columnResizeMode: 'onChange',
            columnResizeDirection: 'ltr',
            manualPagination: true,
            meta: {
                updateData: (rowId, columnId, value)=>{
                    if (onCellUpdate) {
                        onCellUpdate(rowId, columnId, value);
                    }
                }
            }
        });
        return /*#__PURE__*/ _react.default.createElement(Root, {
            ref: rootRef,
            view: view,
            size: size,
            className: (0, _classnames.default)(props.className, classNames?.root, _Tabletokens.classes.root),
            ...props
        }, topContent, /*#__PURE__*/ _react.default.createElement(_Tablestyles.ScrollableWrapper, {
            className: _Tabletokens.classes.scrollableContainer,
            onScroll: onScroll,
            maxHeight: maxHeight
        }, /*#__PURE__*/ _react.default.createElement(_Tablestyles.Table, {
            borderVariant: borderVariant,
            stickyHeader: stickyHeader,
            className: (0, _classnames.default)(classNames?.table, _Tabletokens.classes.table)
        }, /*#__PURE__*/ _react.default.createElement(_Tablestyles.Thead, {
            view: view,
            borderVariant: borderVariant,
            stickyHeader: stickyHeader,
            className: (0, _classnames.default)(classNames?.header?.wrapper, _Tabletokens.classes.headerWrapper)
        }, table.getHeaderGroups().map((headerGroup)=>/*#__PURE__*/ _react.default.createElement(_Tablestyles.Tr, {
                key: headerGroup.id,
                className: (0, _classnames.default)(classNames?.header?.row, _Tabletokens.classes.headerRow)
            }, headerGroup.headers.map((header)=>/*#__PURE__*/ _react.default.createElement(_ui.HeadCell, {
                    key: header.index,
                    header: header,
                    size: size,
                    borderVariant: borderVariant,
                    outerFiltered: outerFiltered,
                    tableContainerRef: tableContainerRef,
                    className: (0, _classnames.default)(classNames?.header?.cell, _Tabletokens.classes.headerCell)
                }))))), /*#__PURE__*/ _react.default.createElement(_Tablestyles.Tbody, {
            className: (0, _classnames.default)(classNames?.body?.wrapper, _Tabletokens.classes.bodyWrapper)
        }, table.getRowModel().rows.map((row)=>/*#__PURE__*/ _react.default.createElement(_Tablestyles.Tr, {
                key: row.id,
                selected: row.getIsSelected(),
                className: (0, _classnames.default)(classNames?.body?.row, _Tabletokens.classes.bodyRow),
                ...setRowProps?.(row.original)
            }, row.getVisibleCells().map((cell)=>{
                const additionalProps = cell?.column?.columnDef?.meta?.setCellProps?.(cell.row.original, cell.id) || {};
                return cell?.column?.columnDef?.meta?.enableEditing ? /*#__PURE__*/ _react.default.createElement(_ui.EditableCell, {
                    key: cell.id,
                    size: size,
                    cell: cell,
                    borderVariant: borderVariant,
                    table: table,
                    selected: row.getIsSelected(),
                    view: view,
                    additionalProps: additionalProps,
                    className: (0, _classnames.default)(classNames?.body?.cell, _Tabletokens.classes.bodyCell)
                }) : /*#__PURE__*/ _react.default.createElement(_ui.Cell, {
                    key: cell.id,
                    cell: cell,
                    borderVariant: borderVariant,
                    selected: row.getIsSelected(),
                    view: view,
                    additionalProps: additionalProps,
                    className: (0, _classnames.default)(classNames?.body?.cell, _Tabletokens.classes.bodyCell)
                });
            }))))), loadingSlot), bottomContent);
    });
const tableConfig = {
    name: 'Table',
    tag: 'div',
    layout: tableRoot,
    base: _Tablestyles.base,
    variations: {},
    defaults: {
        view: 'default',
        size: 'm'
    }
};
