'use client';

import React, { ReactNode, useEffect, useRef } from 'react'
import { CellMeasurerCache, AutoSizer, CellMeasurer, List } from 'react-virtualized';

type Props = {
    children: Array<ReactNode>;
    rowHeight?: number;
} & React.OlHTMLAttributes<HTMLUListElement>;

const cache = new CellMeasurerCache({
    fixedWidth: true,
    defaultHeight: 100,
});

function PerformantTabRenderer({ children, rowHeight = 100, ...rest }: Props) {
    const listRef: React.Ref<List> | undefined = useRef(null)

    useEffect(() => {
        const timeout = setTimeout(() => {
            cache.clearAll();
            listRef.current?.recomputeRowHeights();
        }, 0); // 1 frame delay

        const updateVh = () => {
            const vh = window.innerHeight * 0.01;
            document.documentElement.style.setProperty('--vh', `${vh}px`);
        };

        updateVh();
        window.addEventListener('resize', updateVh);
        window.addEventListener('orientationchange', updateVh);

        return () => {
            window.removeEventListener('resize', updateVh);
            window.removeEventListener('orientationchange', updateVh);
            clearTimeout(timeout);
        };
    }, [children]);

    return (
        <ul
            {...rest}
            style={{
                height: (rowHeight * children.length),
                paddingTop: 16,
            }}
        >
            <AutoSizer>
                {({ height, width }) => (
                    <List
                        style={{
                            direction: "rtl",
                            position: "relative",
                            WebkitOverflowScrolling: "touch",
                            overflowX: "auto",
                            overflowY: "hidden",
                        }} // optional
                        ref={listRef}
                        width={width}
                        height={height}
                        rowCount={children.length}
                        rowHeight={cache.rowHeight}
                        rowRenderer={({ index, key, style, parent }) => (
                            <CellMeasurer
                                key={key}
                                cache={cache}
                                parent={parent}
                                columnIndex={0}
                                rowIndex={index}
                            >
                                {({ measure }) => (
                                    <li style={style} dir='rtl'>
                                        <div onLoad={measure}>
                                            {children[index]}
                                        </div>
                                    </li>
                                )}
                            </CellMeasurer>
                        )}

                    />
                )}
            </AutoSizer>
        </ul>
    )
}

export default PerformantTabRenderer