import { __assign, __awaiter, __generator } from "tslib";
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo } from "react";
import { useMantineReactTable, MantineReactTable, MRT_EditActionButtons as EditActionButtonsMRT, } from "mantine-react-table";
import { Flex, Text, Stack, Title } from "@mantine/core";
import { RowActions, TableEmptyState, TopToolbar } from "./components";
import { paginationBaseConfig } from "./hooks";
// utils & styles
import { defaultCrudAccess, getAnalyticsCategory, onCreatingRowSave, onEditingRowSave, } from "./utils";
import { updateValues } from "../../utils";
export function Table(_a) {
    var _this = this;
    var columns = _a.columns, data = _a.data, tableName = _a.tableName, tableOptions = _a.tableOptions, isLoading = _a.isLoading, reloadFn = _a.reloadFn, crudOptions = _a.crudOptions, _b = _a.disableCrud, disableCrudOperations = _b === void 0 ? false : _b, _c = _a.crudAccess, crudAccess = _c === void 0 ? defaultCrudAccess : _c, EmptyStateComponent = _a.EmptyStateComponent, detailPanelRender = _a.renderDetailPanel, debugRows = _a.debugRows, _d = _a.rowActionsPosition, rowActionsPosition = _d === void 0 ? "end" : _d, _e = _a.disablePagination, disablePagination = _e === void 0 ? false : _e, _f = _a.hideOuterBorder, hideOuterBorder = _f === void 0 ? false : _f, setTableConfig = _a.setTableConfig, totalRecords = _a.totalRecords, rowActionMenuItems = _a.rowActionMenuItems, onDoubleClickRow = _a.onDoubleClickRow;
    var access = updateValues(defaultCrudAccess, crudAccess);
    // if user has explicitly specified allAccess to false, then disable CRUD functionality
    // otherwise use the value of disableCrud Prop
    var disableCrud = !access.allAccess || disableCrudOperations;
    var hasEditAccess = access.editAccess && !disableCrud;
    var hasCreateAccess = access.createAccess && !disableCrud;
    var hasDeleteAccess = access.deleteAccess && !disableCrud;
    var crud_access = {
        editAccess: hasEditAccess,
        createAccess: hasCreateAccess,
        deleteAccess: hasDeleteAccess,
        allAccess: crudAccess.allAccess,
    };
    var setTableRowObject = (crudOptions !== null && crudOptions !== void 0 ? crudOptions : {}).setTableRowObject;
    var anayticsCategory = getAnalyticsCategory(tableName, disableCrud);
    var tableConfig = __assign(__assign(__assign({ columns: columns, data: data, enableColumnActions: false, enableRowSelection: false, enableRowActions: true, enableRowNumbers: false, enableTableHead: true, enableTableFooter: true, enableExpanding: Boolean(detailPanelRender), enableColumnResizing: false, enableDensityToggle: false, enableFullScreenToggle: false, enableGlobalFilterModes: true, enableEditing: hasEditAccess, rowNumberMode: "original", positionGlobalFilter: "left", enableStickyHeader: true, enablePagination: !disablePagination, enableBottomToolbar: !disablePagination, positionActionsColumn: rowActionsPosition === "start" ? "first" : "last" }, (totalRecords && {
        manualPagination: true,
        rowCount: totalRecords,
    })), { mantineSearchTextInputProps: {
            variant: "default",
            radius: 6,
        }, mantineTableProps: {
            verticalSpacing: "md",
            sx: {
                scrollBehavior: "initial",
                tableLayout: "fixed",
            },
        }, mantineSkeletonProps: {
            animate: false,
            width: "100%",
        }, mantineTableContainerProps: {
            sx: {
                paddingInline: 16,
            },
        }, mantineTopToolbarProps: {
            sx: {
                paddingInline: 22,
            },
        }, state: {
            isLoading: isLoading,
            showGlobalFilter: true,
        }, initialState: {
            showGlobalFilter: true,
        }, mantinePaperProps: {
            withBorder: !hideOuterBorder,
            sx: {
                borderRadius: "8px",
            },
        } }), tableOptions);
    var enableEditing = tableConfig.enableRowActions && tableConfig.enableEditing;
    var tableRenderConfig = __assign(__assign(__assign(__assign(__assign({}, tableConfig), { enableEditing: enableEditing, mantineEditRowModalProps: function () { return ({
            returnFocus: true,
            radius: "lg",
            lockScroll: false,
            closeOnClickOutside: false,
            withCloseButton: true,
            closeButtonProps: {
                mr: 10,
                size: "md",
            },
        }); }, onEditingRowSave: function (e) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!enableEditing) return [3 /*break*/, 2];
                        return [4 /*yield*/, onEditingRowSave({
                                e: e,
                                tableName: tableName,
                                crudOptions: crudOptions !== null && crudOptions !== void 0 ? crudOptions : {},
                                anayticsCategory: anayticsCategory,
                            })];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        }); }, onEditingRowCancel: function () {
            setTableRowObject === null || setTableRowObject === void 0 ? void 0 : setTableRowObject({});
        }, onCreatingRowCancel: function () {
            setTableRowObject === null || setTableRowObject === void 0 ? void 0 : setTableRowObject({});
        }, onCreatingRowSave: function (e) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, onCreatingRowSave({
                            e: e,
                            tableName: tableName,
                            crudOptions: crudOptions !== null && crudOptions !== void 0 ? crudOptions : {},
                            anayticsCategory: anayticsCategory,
                        })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); }, mantineTableBodyCellProps: function (_a) {
            var table = _a.table, row = _a.row;
            return ({
                sx: {
                    backgroundColor: "transparent",
                },
                onDoubleClick: function () {
                    if (onDoubleClickRow) {
                        onDoubleClickRow(row.original);
                        return;
                    }
                    // double click to set editing
                    if (enableEditing) {
                        setTableRowObject === null || setTableRowObject === void 0 ? void 0 : setTableRowObject(row.original);
                        table.setEditingRow(row);
                    }
                },
            });
        }, renderEditRowModalContent: function (_a) {
            var table = _a.table, row = _a.row, internalEditComponents = _a.internalEditComponents;
            return (_jsxs(Stack, { children: [_jsxs(Title, { order: 3, children: ["Edit ", tableName] }), internalEditComponents, _jsx(Flex, { justify: "flex-end", mt: "xl", children: _jsx(EditActionButtonsMRT, { variant: "text", table: table, row: row }) })] }));
        }, renderCreateRowModalContent: function (_a) {
            var table = _a.table, row = _a.row, internalEditComponents = _a.internalEditComponents;
            return (_jsxs(Stack, { children: [_jsxs(Title, { order: 3, children: ["Add ", tableName] }), internalEditComponents, _jsx(Flex, { justify: "flex-end", mt: "xl", children: _jsx(EditActionButtonsMRT, { variant: "text", table: table, row: row }) })] }));
        }, renderRowActions: function (_a) {
            var row = _a.row, table = _a.table;
            return tableConfig.enableRowActions && (_jsx(RowActions, { table: table, disableCrud: disableCrud, crudAccess: crud_access, anayticsCategory: anayticsCategory, columns: columns, tableOptions: tableOptions, tableName: tableName, row: row, crudOptions: crudOptions, rowActionMenuItems: rowActionMenuItems }));
        } }), (tableConfig.enableExpanding && {
        renderDetailPanel: function (_a) {
            var row = _a.row;
            return tableConfig.enableExpanding && (_jsx(_Fragment, { children: !detailPanelRender ? (_jsx(Text, { children: "No Description Provided... Yet..." })) : (detailPanelRender(row.original)) }));
        },
    })), { renderTopToolbarCustomActions: function (_a) {
            var table = _a.table;
            return (_jsx(TopToolbar, { table: table, crudAccess: crud_access, anayticsCategory: anayticsCategory, columns: columns, tableOptions: tableOptions, tableName: tableName }));
        }, renderEmptyRowsFallback: function () { return (_jsx(_Fragment, { children: !EmptyStateComponent ? (_jsx(TableEmptyState, { tableName: tableName, reloadFn: reloadFn })) : (EmptyStateComponent) })); } }), tableOptions);
    var table = useMantineReactTable(tableRenderConfig);
    var tablePagination = table.getState().pagination;
    var paginationValue = useMemo(function () {
        var pagination = tablePagination
            ? __assign(__assign({}, tablePagination), { pageIndex: tablePagination.pageIndex + 1 }) : paginationBaseConfig;
        return pagination;
    }, [tablePagination]);
    useEffect(function () {
        var values = {
            tableInstance: table,
            tableName: tableName,
            paginationData: paginationValue,
        };
        setTableConfig === null || setTableConfig === void 0 ? void 0 : setTableConfig(values);
    }, [paginationValue, setTableConfig, table, tableName]);
    if (debugRows) {
        console.log("".concat(tableName, " Table Data"), table.getCoreRowModel().rows.map(function (row) { return row.original; }));
    }
    return _jsx(MantineReactTable, { table: table });
}
