'use strict';

var jsxRuntime = require('../node_modules/.pnpm/react@18.2.0/node_modules/react/jsx-runtime.cjs');
var reactIcons_esm = require('../node_modules/.pnpm/@radix-ui_react-icons@1.3.0_react@18.2.0/node_modules/@radix-ui/react-icons/dist/react-icons.esm.cjs');
var index$1 = require('../node_modules/.pnpm/@tanstack_react-table@8.9.2_react-dom@18.3.1_react@18.2.0__react@18.2.0/node_modules/@tanstack/react-table/build/lib/index.cjs');
var React = require('react');
var flex = require('../flex/flex.cjs');
var text = require('../text/text.cjs');
var DataTableClearFilter = require('./DataTableClearFilter.cjs');
var DataTableFilterChips = require('./DataTableFilterChips.cjs');
var DataTableFilterOptions = require('./DataTableFilterOptions.cjs');
var DataTableFooter = require('./DataTableFooter.cjs');
var DataTableGloabalSearch = require('./DataTableGloabalSearch.cjs');
var DataTableToolbar = require('./DataTableToolbar.cjs');
var DataTableViewOptions = require('./DataTableViewOptions.cjs');
var TableContext = require('./TableContext.cjs');
var TableDetailContainer = require('./TableDetailContainer.cjs');
var datatable_module = require('./datatable.module.css.cjs');
var useTableColumn = require('./hooks/useTableColumn.cjs');
var table = require('./table.cjs');
var index = require('../node_modules/.pnpm/react-loading-skeleton@3.4.0_react@18.2.0/node_modules/react-loading-skeleton/dist/index.cjs');
var index$2 = require('../node_modules/.pnpm/@tanstack_table-core@8.9.2/node_modules/@tanstack/table-core/build/lib/index.cjs');

function DataTableRoot({ columns, data, emptyState, children, parentStyle, isLoading = false, ShouldShowHeader = true, initialState, loaderRow = 2, onRowClick, onStateChange = () => { }, onLoadMore, ...props }) {
    const [tableCustomFilter, setTableCustomFilter] = React.useState({});
    const convertedChildren = React.Children.toArray(children);
    const header = convertedChildren.find((child) => child.type === DataTableToolbar.DataTableToolbar) || null;
    const footer = convertedChildren.find((child) => child.type === DataTableFooter.DataTableFooter) || null;
    const detail = convertedChildren.find((child) => child.type === TableDetailContainer.TableDetailContainer) ||
        null;
    const [tableState, setTableState] = React.useState({});
    const observerRef = React.useRef(null);
    const lastRowRef = React.useRef(null);
    React.useEffect(() => {
        if (!onLoadMore)
            return;
        const observer = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting && !isLoading) {
                onLoadMore();
            }
        }, { threshold: 0.1 });
        observerRef.current = observer;
        return () => observer.disconnect();
    }, [onLoadMore, isLoading]);
    React.useEffect(() => {
        const observer = observerRef.current;
        const lastRow = lastRowRef.current;
        if (observer && lastRow) {
            observer.disconnect();
            observer.observe(lastRow);
        }
        return () => {
            if (observer && lastRow) {
                observer.unobserve(lastRow);
            }
        };
    }, [isLoading]);
    const getLoader = (loaderRow, columns) => ([...new Array(loaderRow)].map((_, rowIndex) => (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Row, { children: columns.map((_, colIndex) => (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Cell, { children: jsxRuntime.jsxRuntimeExports.jsx(index.default, { containerClassName: datatable_module.default.flex1, highlightColor: "var(--background-base)", baseColor: "var(--background-base-hover)" }) }, `col_${colIndex}`))) }, `row_${rowIndex}`))));
    const tableData = onLoadMore ? data : (isLoading
        ? [...new Array(loaderRow)].map((_, i) => ({ id: i }))
        : data);
    const { filteredColumns, addFilterColumn, removeFilterColumn, resetColumns } = useTableColumn.useTableColumn();
    const columnWithCustomFilter = React.useMemo(() => columns.map((col) => {
        const colId = col.id || col?.accessorKey;
        const filterFn = colId && tableCustomFilter.hasOwnProperty(colId)
            ? tableCustomFilter[colId]
            : undefined;
        const cell = onLoadMore
            ? col.cell
            : (isLoading
                ? () => (jsxRuntime.jsxRuntimeExports.jsx(index.default, { containerClassName: datatable_module.default.flex1, highlightColor: "var(--background-base)", baseColor: "var(--background-base-hover)" }))
                : col.cell);
        return {
            ...col,
            cell,
            filterFn,
        };
    }), [isLoading, columns, tableCustomFilter, onLoadMore]);
    React.useEffect(() => {
        if (onStateChange) {
            onStateChange(tableState);
        }
    }, [tableState]);
    const updateColumnCustomFilter = (id, filterFn) => {
        setTableCustomFilter((old) => ({ ...old, [id]: filterFn }));
    };
    const table$1 = index$1.useReactTable({
        data: tableData,
        columns: columnWithCustomFilter,
        globalFilterFn: "auto",
        enableRowSelection: true,
        manualPagination: true,
        pageCount: -1,
        onStateChange: (updater) => setTableState(updater),
        getCoreRowModel: index$2.getCoreRowModel(),
        getFilteredRowModel: index$2.getFilteredRowModel(),
        getPaginationRowModel: index$2.getPaginationRowModel(),
        getSortedRowModel: index$2.getSortedRowModel(),
        getFacetedRowModel: index$2.getFacetedRowModel(),
        getFacetedUniqueValues: index$2.getFacetedUniqueValues(),
        initialState,
        state: tableState,
    });
    const tableStyle = {
        ...(table$1.getRowModel().rows?.length
            ? { width: "100%" }
            : { width: "100%", height: "100%" }),
        ...{ borderCollapse: "collapse" },
    };
    return (jsxRuntime.jsxRuntimeExports.jsx(flex.Flex, { direction: "column", justify: "between", className: datatable_module.default.wrapper, children: jsxRuntime.jsxRuntimeExports.jsxs(TableContext.TableContext.Provider, { value: {
                table: table$1,
                globalFilter: tableState.globalFilter,
                filteredColumns,
                addFilterColumn,
                removeFilterColumn,
                resetColumns,
                onGlobalFilterChange: (value) => setTableState((prev) => ({ ...prev, globalFilter: value })),
                onChange: () => ({}),
                tableCustomFilter,
                updateColumnCustomFilter,
                isLoading,
            }, children: [jsxRuntime.jsxRuntimeExports.jsxs(flex.Flex, { direction: "column", className: datatable_module.default.datatable, children: [header, jsxRuntime.jsxRuntimeExports.jsxs(flex.Flex, { className: datatable_module.default.tableContainer, style: parentStyle, children: [jsxRuntime.jsxRuntimeExports.jsxs(table.Table, { ...props, style: tableStyle, children: [jsxRuntime.jsxRuntimeExports.jsx(table.Table.Header, { className: datatable_module.default.header, children: ShouldShowHeader
                                                ? table$1.getHeaderGroups().map((headerGroup) => (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Row, { children: headerGroup.headers.map((header, index) => {
                                                        return (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Head, { style: {
                                                                cursor: "pointer",
                                                                ...(header.column.columnDef?.meta?.style ?? {}),
                                                            }, onClick: header.column.getToggleSortingHandler(), children: jsxRuntime.jsxRuntimeExports.jsxs(text.Text, { className: datatable_module.default.head, children: [header.isPlaceholder
                                                                        ? null
                                                                        : index$1.flexRender(header.column.columnDef.header, header.getContext()), header.column.getCanSort()
                                                                        ? {
                                                                            asc: jsxRuntime.jsxRuntimeExports.jsx(reactIcons_esm.CaretUpIcon, {}),
                                                                            desc: jsxRuntime.jsxRuntimeExports.jsx(reactIcons_esm.CaretDownIcon, {}),
                                                                        }[header.column.getIsSorted()] ?? jsxRuntime.jsxRuntimeExports.jsx(reactIcons_esm.CaretSortIcon, {})
                                                                        : null] }) }, `${header.id}_${index}`));
                                                    }) }, headerGroup.id)))
                                                : null }), jsxRuntime.jsxRuntimeExports.jsxs(table.Table.Body, { children: [table$1.getRowModel().rows?.length ? (table$1.getRowModel().rows.map((row, rowIndex) => (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Row, { "data-state": row.getIsSelected() && "selected", onClick: () => onRowClick?.(row.original), className: isLoading
                                                        ? ""
                                                        : `${datatable_module.default.tRow} ${onRowClick ? datatable_module.default.tRowClick : ""}`, ref: onLoadMore && rowIndex === table$1.getRowModel().rows.length - 1
                                                        ? lastRowRef
                                                        : null, children: row.getVisibleCells().map((cell, index) => (jsxRuntime.jsxRuntimeExports.jsx(table.Table.Cell, { style: {
                                                            ...(cell.column.columnDef?.meta?.style ?? {}),
                                                        }, children: index$1.flexRender(cell.column.columnDef.cell, cell.getContext()) }, `${cell.id}_${index}`))) }, row.id)))) : (!isLoading ?
                                                    jsxRuntime.jsxRuntimeExports.jsx(table.Table.Row, { children: jsxRuntime.jsxRuntimeExports.jsx(table.Table.Cell, { colSpan: columns.length, children: emptyState || "No results." }) }) : jsxRuntime.jsxRuntimeExports.jsx(jsxRuntime.jsxRuntimeExports.Fragment, {})), isLoading && onLoadMore && getLoader(loaderRow, columns)] })] }), detail] })] }), footer] }) }));
}
const DataTable = Object.assign(DataTableRoot, {
    Toolbar: DataTableToolbar.DataTableToolbar,
    GloabalSearch: DataTableGloabalSearch.DataTableGloabalSearch,
    FilterOptions: DataTableFilterOptions.DataTableFilterOptions,
    ViewOptions: DataTableViewOptions.DataTableViewOptions,
    ClearFilter: DataTableClearFilter.DataTableClearFilter,
    FilterChips: DataTableFilterChips.DataTableFilterChips,
    Footer: DataTableFooter.DataTableFooter,
    DetailContainer: TableDetailContainer.TableDetailContainer,
});

exports.DataTable = DataTable;
//# sourceMappingURL=datatable.cjs.map
