import React, { FC, useRef } from 'react';
import { InfiniteListLoaderProps } from './InifniteListLoader.types';

import {
    AutoSizer as _AutoSizer,
    List as _List,
    CellMeasurer as _CellMeasurer,
    CellMeasurerCache,
    ListProps,
    AutoSizerProps,
    CellMeasurerProps,
} from "react-virtualized";

const List = _List as unknown as FC<ListProps>;
const AutoSizer = _AutoSizer as unknown as FC<AutoSizerProps>;
const CellMeasurer = _CellMeasurer as unknown as FC<CellMeasurerProps>

export const InfiniteListLoader: FC<InfiniteListLoaderProps> = ({
    values,  
    itemHeight = 100,
    extraRows = 5,
    renderItem,
}) => {

    const cache = useRef(new CellMeasurerCache({
        fixedWidth: true,
        defaultHeight: itemHeight
    }))

    return(
        <AutoSizer>
            {({width, height}) => (
                <List
                    width={width}
                    height={height}
                    rowHeight={cache.current.rowHeight}
                    overscanRowCount={extraRows}
                    rowCount={values.length}
                    rowRenderer={({key, index, style, parent}) => {
                        return ( 
                            <CellMeasurer 
                                key={key} 
                                cache={cache.current} 
                                parent={parent}
                                columnIndex={extraRows}
                                rowIndex={index}
                            >
                                <div key={key} style={style}>
                                    {renderItem(values, index, key)}
                                </div>
                            </CellMeasurer>
                        );
                    }}
                />
            )}
        </AutoSizer>
    );
}