import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useRef, useState } from "react";
import { flexRender } from "@tanstack/react-table";
import { useVirtualizer } from "@tanstack/react-virtual";
import { cn } from "@utils";
import { Loader } from "../loader/loader";
import { ADPIcon, iconList } from "../adpIcon/adpIcon";
import { EmptyState } from "../emptyState/emptyState";
import { dataTableVariants, dataTableHeadVariants, dataTableHeaderCellVariants, dataTableCellVariants, dataTableSelectableVariants, dataTableResizerVariants, dataTableEmptyStateVariants } from "./dataTableVariants";
export const Table = ({ table, columnVirtualization = false, rowVirtualization = false, selectable = false, resizable = false, loading = false, height, isRtl = false }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const tableContainerRef = useRef(null);
    const [highlightFirstRow, setHighlightFirstRow] = useState();
    const { rows } = table.getRowModel();
    const visibleColumns = table.getVisibleLeafColumns();
    const columnVirtualizer = useVirtualizer({
        count: visibleColumns.length,
        estimateSize: (index) => visibleColumns[index].getSize(),
        getScrollElement: () => tableContainerRef.current,
        horizontal: true,
        overscan: 50
    });
    const rowVirtualizer = useVirtualizer({
        count: rows.length,
        estimateSize: () => 56,
        getScrollElement: () => tableContainerRef.current,
        //measure dynamic row height, except in firefox because it measures table border height incorrectly
        measureElement: typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
            ? (element) => element === null || element === void 0 ? void 0 : element.getBoundingClientRect().height
            : undefined,
        overscan: 10
    });
    const virtualColumns = columnVirtualization ? columnVirtualizer.getVirtualItems() : [];
    const virtualRows = rowVirtualization ? rowVirtualizer.getVirtualItems() : [];
    let virtualPaddingLeft;
    let virtualPaddingRight;
    if (columnVirtualization && (virtualColumns === null || virtualColumns === void 0 ? void 0 : virtualColumns.length)) {
        virtualPaddingLeft = (_b = (_a = virtualColumns[0]) === null || _a === void 0 ? void 0 : _a.start) !== null && _b !== void 0 ? _b : 0;
        virtualPaddingRight = columnVirtualizer.getTotalSize() - ((_d = (_c = virtualColumns[virtualColumns.length - 1]) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : 0);
    }
    const getCommonPinningStyles = (column) => {
        const isPinned = column.getIsPinned();
        const styles = {
            position: isPinned ? "sticky" : "relative",
            zIndex: isPinned ? 1 : 0,
            boxShadow: isPinned ? "0 4px 32px -2px rgba(27, 37, 51, 0.06)" : "none"
        };
        // Adjust for RTL mode
        if (isPinned) {
            if (isRtl) {
                if (isPinned === "left") {
                    styles.right = `${column.getStart("right")}px`;
                }
                else if (isPinned === "right") {
                    styles.left = `${column.getStart("left")}px`;
                }
            }
            else {
                if (isPinned === "left") {
                    styles.left = `${column.getStart("left")}px`;
                }
                else if (isPinned === "right") {
                    styles.right = `${column.getStart("right")}px`;
                }
            }
        }
        return styles;
    };
    return (_jsx("div", { ref: tableContainerRef, className: "overflow-auto max-h-full", style: { height: rowVirtualization ? "calc(100% - 20px)" : height }, children: _jsxs("table", { className: cn(dataTableVariants()), style: { width: "100%" }, children: [_jsx("thead", { className: cn(dataTableHeadVariants()), children: columnVirtualization
                        ? (_jsx(_Fragment, { children: (_e = table === null || table === void 0 ? void 0 : table.getHeaderGroups()) === null || _e === void 0 ? void 0 : _e.map((headerGroup) => (_jsxs("tr", { children: [virtualPaddingLeft ? (
                                    //fake empty column to the left for virtualization scroll padding
                                    _jsx("th", { style: { display: "flex", width: virtualPaddingLeft } })) : null, virtualColumns.map((vc) => {
                                        var _a;
                                        const header = headerGroup.headers[vc === null || vc === void 0 ? void 0 : vc.index];
                                        return (_jsxs("th", { className: cn(dataTableHeaderCellVariants(), selectable && dataTableSelectableVariants()), style: Object.assign(Object.assign({}, getCommonPinningStyles(header.column)), { width: header.getSize() }), children: [_jsxs("div", { className: cn("flex items-center gap-1", header.column.getCanSort() ? "cursor-pointer select-none" : ""), onClick: header.column.getToggleSortingHandler(), children: [flexRender(header.column.columnDef.header, header.getContext()), (_a = {
                                                            asc: (_jsx(ADPIcon, { icon: iconList.upArrowLong, className: "inline-flex ml-1", size: "xs" })),
                                                            desc: (_jsx(ADPIcon, { icon: iconList.downArrowLong, className: "inline-flex ml-1", size: "xs" }))
                                                        }[header.column.getIsSorted()]) !== null && _a !== void 0 ? _a : null] }), resizable && header.column.getCanResize() && (_jsx("div", { className: cn(dataTableResizerVariants({
                                                        direction: isRtl ? "rtl" : "ltr",
                                                        isResizing: header.column.getIsResizing()
                                                    })), onMouseDown: header.getResizeHandler(), onTouchStart: header.getResizeHandler() }))] }, header.id));
                                    }), virtualPaddingRight ? (
                                    //fake empty column to the right for virtualization scroll padding
                                    _jsx("th", { style: { display: "flex", width: virtualPaddingRight } })) : null] }, headerGroup.id))) }))
                        : (_jsx(_Fragment, { children: (_f = table === null || table === void 0 ? void 0 : table.getHeaderGroups()) === null || _f === void 0 ? void 0 : _f.map((headerGroup) => (_jsx("tr", { children: headerGroup.headers.map((header) => {
                                    var _a;
                                    return (_jsxs("th", { className: cn(dataTableHeaderCellVariants(), selectable && dataTableSelectableVariants()), style: Object.assign(Object.assign({}, getCommonPinningStyles(header.column)), { width: header.getSize() }), children: [_jsxs("div", { className: cn("flex items-center gap-1", header.column.getCanSort() ? "cursor-pointer select-none" : ""), onClick: header.column.getToggleSortingHandler(), children: [flexRender(header.column.columnDef.header, header.getContext()), (_a = {
                                                        asc: (_jsx(ADPIcon, { icon: iconList.upArrowLong, className: "inline-flex ml-1", size: "xs" })),
                                                        desc: (_jsx(ADPIcon, { icon: iconList.downArrowLong, className: "inline-flex ml-1", size: "xs" }))
                                                    }[header.column.getIsSorted()]) !== null && _a !== void 0 ? _a : null] }), resizable && header.column.getCanResize() && (_jsx("div", { className: cn(dataTableResizerVariants({
                                                    direction: isRtl ? "rtl" : "ltr",
                                                    isResizing: header.column.getIsResizing()
                                                })), onMouseDown: header.getResizeHandler(), onTouchStart: header.getResizeHandler() }))] }, header.id));
                                }) }, headerGroup.id))) })) }), _jsx("tbody", { children: loading ? (_jsx("tr", { className: "h-full", children: _jsx("td", { colSpan: table.getAllColumns().length, className: "text-center", children: _jsx(Loader, {}) }) })) : rows.length === 0 ? (_jsx("tr", { children: _jsx("td", { colSpan: table.getAllColumns().length, children: _jsx("div", { className: cn(dataTableEmptyStateVariants()), children: _jsx(EmptyState, { imageVariant: "analytics", children: _jsx(EmptyState.Content, { className: "text-md text-secondary-500 font-semibold dark:text-secondary-50", children: "There are no records available" }) }) }) }) })) : rowVirtualization ? (_jsxs(_Fragment, { children: [virtualRows.length > 0 && (_jsx("tr", { style: { height: `${((_g = virtualRows[0]) === null || _g === void 0 ? void 0 : _g.start) || 0}px` }, children: _jsx("td", { colSpan: table.getAllColumns().length }) })), virtualRows.map((virtualRow) => {
                                const row = rows[virtualRow.index];
                                return (_jsx("tr", { "data-index": virtualRow.index, ref: (node) => rowVirtualizer.measureElement(node), children: columnVirtualization ? (_jsxs(_Fragment, { children: [virtualPaddingLeft ? (_jsx("td", { style: { display: "flex", width: virtualPaddingLeft } })) : null, virtualColumns.map((vc) => {
                                                const cell = row.getVisibleCells()[vc.index];
                                                return (_jsx("td", { className: cn(dataTableCellVariants(), selectable && dataTableSelectableVariants(), highlightFirstRow === row.id ? "bg-gray-50 dark:bg-secondary-600" : "bg-white dark:bg-iridium"), style: Object.assign(Object.assign({}, getCommonPinningStyles(cell.column)), { width: cell.column.getSize(), wordBreak: "break-word" }), onMouseEnter: () => setHighlightFirstRow(row.id), onMouseLeave: () => setHighlightFirstRow(null), children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id));
                                            }), virtualPaddingRight ? (_jsx("td", { style: { display: "flex", width: virtualPaddingRight } })) : null] })) : (row.getVisibleCells().map((cell) => (_jsx("td", { className: cn(dataTableCellVariants(), selectable && dataTableSelectableVariants(), highlightFirstRow === row.id ? "bg-gray-50 dark:bg-secondary-600" : "bg-white dark:bg-iridium"), style: Object.assign(Object.assign({}, getCommonPinningStyles(cell.column)), { width: cell.column.getSize(), wordBreak: "break-word" }), onMouseEnter: () => setHighlightFirstRow(row.id), onMouseLeave: () => setHighlightFirstRow(null), children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id)))) }, row.id));
                            }), _jsx("tr", { style: {
                                    height: `${rowVirtualizer.getTotalSize() -
                                        (((_h = virtualRows[virtualRows.length - 1]) === null || _h === void 0 ? void 0 : _h.end) || 0)}px`
                                }, children: _jsx("td", { colSpan: table.getAllColumns().length }) })] })) : (
                    // Non-virtualized rows
                    table.getRowModel().rows.map((row) => (_jsx("tr", { children: row.getVisibleCells().map((cell) => (_jsx("td", { className: cn(dataTableCellVariants(), selectable && dataTableSelectableVariants(), highlightFirstRow === row.id ? "bg-gray-50 dark:bg-secondary-600" : "bg-white dark:bg-iridium"), style: Object.assign(Object.assign({}, getCommonPinningStyles(cell.column)), { width: cell.column.getSize(), wordBreak: "break-word" }), onMouseEnter: () => setHighlightFirstRow(row.id), onMouseLeave: () => setHighlightFirstRow(null), children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))) }, row.id)))) })] }) }));
};
export default Table;
//# sourceMappingURL=table.js.map