import { j as jsxRuntimeExports } from '../node_modules/.pnpm/react@18.2.0/node_modules/react/jsx-runtime.js';
import { CaretUpIcon, CaretDownIcon, CaretSortIcon } from '../node_modules/.pnpm/@radix-ui_react-icons@1.3.0_react@18.2.0/node_modules/@radix-ui/react-icons/dist/react-icons.esm.js';
import { useReactTable, flexRender } from '../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.js';
import { useState, Children, useRef, useEffect, useMemo } from 'react';
import { Flex } from '../flex/flex.js';
import { Text } from '../text/text.js';
import { DataTableClearFilter } from './DataTableClearFilter.js';
import { DataTableFilterChips } from './DataTableFilterChips.js';
import { DataTableFilterOptions } from './DataTableFilterOptions.js';
import { DataTableFooter } from './DataTableFooter.js';
import { DataTableGloabalSearch } from './DataTableGloabalSearch.js';
import { DataTableToolbar } from './DataTableToolbar.js';
import { DataTableViewOptions } from './DataTableViewOptions.js';
import { TableContext } from './TableContext.js';
import { TableDetailContainer } from './TableDetailContainer.js';
import styles from './datatable.module.css.js';
import { useTableColumn } from './hooks/useTableColumn.js';
import { Table } from './table.js';
import Skeleton from '../node_modules/.pnpm/react-loading-skeleton@3.4.0_react@18.2.0/node_modules/react-loading-skeleton/dist/index.js';
import { getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, getFacetedRowModel, getFacetedUniqueValues } from '../node_modules/.pnpm/@tanstack_table-core@8.9.2/node_modules/@tanstack/table-core/build/lib/index.js';

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

export { DataTable };
//# sourceMappingURL=datatable.js.map
