import classNames from 'classnames';
import { PropTypes } from 'react';

import Spinner from '../aui-react/spinner';
import ScrollHandler from '../scroll-handler/scroll-handler';

const propTypes = {
    allFetched: PropTypes.bool.isRequired,
    allFetchedMessage: PropTypes.string,
    bufferPx: ScrollHandler.propTypes.bufferPx,
    className: PropTypes.string,
    focusedIndex: PropTypes.number,
    header: PropTypes.func,
    items: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    onMoreItemsRequested: PropTypes.func.isRequired,
    row: PropTypes.func.isRequired,
    scrollElement: ScrollHandler.propTypes.scrollElement,
};

const PagedTable = props => {
    const VISIBLE_PRS = 7;
    const rows = props.row ?
        props.items.map((item, i) => {
            return props.row({
                item,
                focused: props.focusedIndex === i,
            });
        }) :
        null;

    return (
        <div className="paged-table-container">
            <ScrollHandler
                bufferPx={props.bufferPx}
                onScrollToBottom={props.onMoreItemsRequested}
                scrollElement={props.scrollElement}
                suspend={props.allFetched || props.loading}
            >
                <table className={classNames("aui paged-table", props.className)}>
                    {props.header && <thead>{props.header()}</thead>}
                    <tbody>{rows}</tbody>
                </table>
            </ScrollHandler>
            {props.loading && <Spinner />}
            {props.allFetched && !props.loading && props.items.length > VISIBLE_PRS && <div className="paged-table-message">{props.allFetchedMessage}</div>}
        </div>
    );
};

PagedTable.propTypes = propTypes;

export default PagedTable;
