import React, { useEffect, useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import { Flex, InfiniteLoader } from "../../../components";
const DefaultLoadingComponent = () => (React.createElement(Flex, { justifyContent: "center", alignItems: "center", height: "76px" },
    React.createElement(InfiniteLoader, null)));
export const VirtualList = ({ itemHeight, overscan = 5, LoadingComponent, isLoading, hasNextPage = false, threshold = 5, onVisibleItemsScrollEnd, items, renderItem, }) => {
    const parentRef = useRef(null);
    const rowVirtualizer = useVirtualizer({
        count: hasNextPage ? items.length + 1 : items.length,
        getScrollElement: () => parentRef.current,
        estimateSize: () => itemHeight,
        overscan,
    });
    useEffect(() => {
        const items = rowVirtualizer.getVirtualItems();
        if (!items.length)
            return;
        const lastItem = items[items.length - 1];
        if (lastItem.index >= items.length - 1 - threshold &&
            hasNextPage &&
            !isLoading &&
            onVisibleItemsScrollEnd) {
            onVisibleItemsScrollEnd();
        }
    }, [
        hasNextPage,
        onVisibleItemsScrollEnd,
        items.length,
        isLoading,
        rowVirtualizer.getVirtualItems(),
    ]);
    const showCustomLoadingComponent = !!LoadingComponent;
    return (React.createElement("div", { ref: parentRef, style: { width: "100%", height: "100%", overflow: "auto" } },
        React.createElement("div", { style: {
                height: `${rowVirtualizer.getTotalSize()}px`,
                width: "100%",
                position: "relative",
            } }, rowVirtualizer.getVirtualItems().map((virtualRow) => (React.createElement("div", { key: virtualRow.index, "data-index": virtualRow.index, ref: rowVirtualizer.measureElement, style: {
                position: "absolute",
                top: 0,
                left: 0,
                transform: `translateY(${virtualRow.start}px)`,
                height: `${itemHeight}px`,
                width: "100%",
            } }, renderItem(items[virtualRow.index]))))),
        isLoading && (showCustomLoadingComponent ? LoadingComponent : React.createElement(DefaultLoadingComponent, null))));
};
//# sourceMappingURL=VirtualList.js.map