"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TableBasic = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_table_1 = require("react-table");
const Flex_1 = require("../Flex");
const Box_1 = require("../Box");
const Text_1 = require("../Text");
const Icon_1 = require("../Icon");
// import { Loading } from '../Loading';
const theme_1 = require("../../theme");
const TablePagination_1 = require("./TablePagination");
const TableBatchActions_1 = require("./TableBatchActions");
const TableEditableCell_1 = require("./TableEditableCell");
const TableRowActions_1 = require("./TableRowActions");
const sc = __importStar(require("./styles"));
function TableBasic({ title, empty, columns, data = [], updateData, batchActions, rowActions, subRow, defaultSort, sortable, selectable, pageSize: pageSizeProp, pageSizes, canSkipPage, isLoading, refresh, lastUpdate, noHeader, onRowClick, getCustomHeaderDefaultColumnProperties, getDefaultCellProperties: getCustomCellDefaultColumnProperties, getCustomRowProperties, rowsIndexesCheckboxesDisabled, rowsIndexesCheckboxesHidden, paginationLabel, selectionRowCellStyle, maxWidth, onSelect, initialSelectedRowIndices, }) {
    const hasData = data.length > 0;
    const paginate = pageSizeProp && pageSizeProp > 1;
    const [skipTableReset, setSkipTableReset] = (0, react_1.useState)(false);
    const [showBatchActions, setShowBatchActions] = (0, react_1.useState)(false);
    const { getTableProps, getTableBodyProps, headerGroups, prepareRow, rows, page, canPreviousPage, canNextPage, nextPage, previousPage, setPageSize, pageCount, gotoPage, toggleRowSelected, state: { pageIndex, pageSize, selectedRowIds }, } = (0, react_table_1.useTable)({
        data,
        columns,
        autoResetPage: !skipTableReset,
        autoResetSortBy: !skipTableReset,
        // autoResetSelectedRows: !skipTableReset,
        initialState: Object.assign(Object.assign(Object.assign({}, (defaultSort
            ? {
                sortBy: [
                    {
                        id: defaultSort.accessor,
                        desc: defaultSort.desc || false,
                    },
                ],
            }
            : {})), { pageIndex: 0 }), (paginate ? { pageSize: pageSizeProp } : {})),
    }, react_table_1.useSortBy, react_table_1.useExpanded, react_table_1.usePagination, react_table_1.useRowSelect, (hooks) => (0, TableRowActions_1.TableRowActions)({
        hooks,
        selectable,
        setShowBatchActions,
        rowActions,
        subRow,
        setSkipTableReset,
        rowsIndexesCheckboxesDisabled,
        rowsIndexesCheckboxesHidden,
    }));
    const selectedRowIndices = Object.keys(selectedRowIds);
    const totalSelectedRows = (0, react_1.useMemo)(() => selectedRowIndices.filter((index) => {
        const indexAsNumber = parseInt(index, 10);
        const disabled = rowsIndexesCheckboxesDisabled === null || rowsIndexesCheckboxesDisabled === void 0 ? void 0 : rowsIndexesCheckboxesDisabled.includes(indexAsNumber);
        const hidden = rowsIndexesCheckboxesHidden === null || rowsIndexesCheckboxesHidden === void 0 ? void 0 : rowsIndexesCheckboxesHidden.includes(indexAsNumber);
        return !disabled && !hidden;
    }).length, [selectedRowIndices, rowsIndexesCheckboxesDisabled]);
    const selectedData = data.filter((entry, index) => selectedRowIndices.includes(`${index}`));
    const isRowSelected = (0, react_1.useCallback)((row, index) => {
        const disabled = rowsIndexesCheckboxesDisabled === null || rowsIndexesCheckboxesDisabled === void 0 ? void 0 : rowsIndexesCheckboxesDisabled.includes(index);
        const hidden = rowsIndexesCheckboxesHidden === null || rowsIndexesCheckboxesHidden === void 0 ? void 0 : rowsIndexesCheckboxesHidden.includes(index);
        return row.isSelected && !disabled && !hidden;
    }, [rowsIndexesCheckboxesDisabled, rowsIndexesCheckboxesHidden]);
    (0, react_1.useEffect)(() => {
        if (initialSelectedRowIndices) {
            initialSelectedRowIndices.forEach((index) => {
                toggleRowSelected(index, true);
            });
        }
    }, [initialSelectedRowIndices]);
    (0, react_1.useEffect)(() => {
        if (onSelect)
            onSelect(selectedData);
    }, [selectedData.length]);
    const InnerWrapper = maxWidth ? sc.TableInnerWrapper : react_1.Fragment;
    return ((0, jsx_runtime_1.jsxs)(sc.TableWrapper, { children: [(title || (!!batchActions && batchActions.length > 0)) && ((0, jsx_runtime_1.jsxs)(Flex_1.Flex, Object.assign({ variant: "basic", justify: "spaced", margin: "0 0 32px 0" }, { children: [(0, jsx_runtime_1.jsx)(Box_1.Box, Object.assign({ variant: "basic" }, { children: title }), void 0), (0, jsx_runtime_1.jsx)(Box_1.Box, Object.assign({ variant: "raw" }, { children: batchActions && batchActions.length > 0 && ((0, jsx_runtime_1.jsx)(TableBatchActions_1.TableBatchActions, { variant: "raw", batchActions: batchActions, showBatchActions: showBatchActions, totalSelectedRows: totalSelectedRows, selectedData: selectedData, selectedRowIndices: selectedRowIndices, refresh: refresh, lastUpdate: lastUpdate, isLoading: isLoading }, void 0)) }), void 0)] }), void 0)), isLoading ? ((0, jsx_runtime_1.jsx)(Flex_1.Flex, Object.assign({ variant: "raw", justify: "center", margin: "l 0" }, { children: "Loading..." }), void 0)) : hasData ? ((0, jsx_runtime_1.jsx)(InnerWrapper, { children: (0, jsx_runtime_1.jsxs)(sc.Table, Object.assign({}, getTableProps(), { children: [!noHeader && ((0, jsx_runtime_1.jsx)(sc.TableHeader, { children: headerGroups.map((headerGroup, rowIndex) => ((0, jsx_runtime_1.jsx)(sc.TableRow, Object.assign({}, headerGroup.getHeaderGroupProps(), (rowIndex === 0 ? { className: 'hide' } : {}), { children: headerGroup.headers.map((column, colIndex) => ((0, jsx_runtime_1.jsx)(sc.TableColumnHeader, Object.assign({}, column.getHeaderProps(sortable
                                    ? column.getSortByToggleProps()
                                    : undefined), (getCustomHeaderDefaultColumnProperties &&
                                    getCustomHeaderDefaultColumnProperties()), (column.getCustomHeaderProperties &&
                                    column.getCustomHeaderProperties()), { children: (0, jsx_runtime_1.jsxs)(Text_1.Text, Object.assign({ variant: "span", format: "b2m", color: column.isSorted ? 'brandMain' : 'gray.2' }, { children: [column.render('Header'), (0, jsx_runtime_1.jsx)("span", { dangerouslySetInnerHTML: {
                                                    __html: column.isSorted
                                                        ? column.isSortedDesc
                                                            ? ' &darr;'
                                                            : ' &uarr;'
                                                        : '',
                                                } }, void 0)] }), void 0) }), `headerRow${rowIndex + 1}Column${colIndex + 1}`))) }), `headerRow${rowIndex + 1}`))) }, void 0)), (0, jsx_runtime_1.jsx)(sc.TableBody, Object.assign({}, getTableBodyProps(), { children: (paginate ? page : rows).map((row, rowIndex) => {
                                prepareRow(row);
                                return ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(sc.TableRow, Object.assign({}, row.getRowProps(), (isRowSelected(row, rowIndex)
                                            ? { className: 'selected' }
                                            : {}), (onRowClick
                                            ? {
                                                onClick: () => onRowClick(row.original, rowIndex),
                                            }
                                            : {}), { paginate: paginate }, (getCustomRowProperties &&
                                            getCustomRowProperties(rowIndex)), { children: row.cells.map((cell, colIndex) => {
                                                return ((0, jsx_runtime_1.jsx)(sc.TableColumn, Object.assign({}, Object.assign(Object.assign(Object.assign(Object.assign({}, cell.getCellProps()), (getCustomCellDefaultColumnProperties &&
                                                    getCustomCellDefaultColumnProperties())), (cell.column.getCustomCellProperties &&
                                                    cell.column.getCustomCellProperties(rowIndex))), (cell.column.id === 'selection' &&
                                                    selectionRowCellStyle)), (cell.column.width
                                                    ? { width: cell.column.width }
                                                    : {}), { children: cell.column.id === 'selection' ||
                                                        cell.column.id === 'deletion' ? (cell.render('Cell')) : ((0, jsx_runtime_1.jsx)(TableEditableCell_1.TableEditableCell, { cell: cell, data: data, updateData: updateData, setSkipTableReset: setSkipTableReset }, void 0)) }), `bodyRow${rowIndex + 1}Column${colIndex + 1}`));
                                            }) }), `bodyRow${rowIndex + 1}`), subRow && row.isExpanded && ((0, jsx_runtime_1.jsx)(sc.TableRow, { children: (0, jsx_runtime_1.jsx)(sc.TableColumn, Object.assign({ colSpan: row.cells.length }, { children: subRow(row.original, row.index) }), void 0) }, `bodyRow${rowIndex + 1}SubRow`))] }, `bodyRow${rowIndex + 1}Fragment`));
                            }) }), void 0)] }), void 0) }, void 0)) : ((0, jsx_runtime_1.jsxs)(Flex_1.Flex, Object.assign({ variant: "raw", justify: "center", dir: "column", margin: "l 0 m 0" }, { children: [empty && empty.icon === false
                        ? null
                        : (empty && empty.icon) || ((0, jsx_runtime_1.jsx)(Icon_1.Icon, { variant: "circle", icon: theme_1.polyIcons.AccountGroup, size: "48px", bg: "gray4", color: "gray3" }, void 0)), empty && empty.copy === false
                        ? null
                        : (empty && empty.copy) || ((0, jsx_runtime_1.jsx)(Text_1.Text, Object.assign({ variant: "span", color: "gray2", margin: "m 0 0 0" }, { children: "No data" }), void 0))] }), void 0)), hasData && paginate && ((0, jsx_runtime_1.jsx)(TablePagination_1.TablePagination, Object.assign({ canPreviousPage: canPreviousPage, canNextPage: canNextPage, nextPage: nextPage, previousPage: previousPage, setPageSize: setPageSize, totalRows: rows.length, pageIndex: pageIndex, pageSize: pageSize, pageSizes: pageSizes }, (canSkipPage
                ? {
                    pageCount,
                    gotoPage,
                }
                : {}), { label: paginationLabel }), void 0))] }, void 0));
}
exports.TableBasic = TableBasic;
//# sourceMappingURL=TableBasic.js.map