import React from 'react';

interface IProps {
    numFound: number;
    pageSize: number;
    p: number;
    show?: boolean;
    onUpdate: (value: number) => void;
}

const defaultProps: Partial<IProps> = {
    show: true
};

export default function Pagination(props: IProps) {
    if (!props.show) { return null; }
    const noOfPages: number = Math.ceil(props.numFound / props.pageSize);

    const pageNumChanged = (e) => {
        let pageNum = e.target.value;
        if (!pageNum) {
            props.onUpdate(pageNum);
            return;
        }

        pageNum = parseInt(e.target.value, 10);
        if (pageNum <= noOfPages && pageNum > 0) {
            props.onUpdate(pageNum);
        }
    };

    return (
        <nav className="se-pagination">
            <ul aria-label="Pagination for results">
                <li>
                    <button aria-label="Go to first page"
                            disabled={(props.p === 1 ? true : false)}
                            onClick={props.onUpdate.bind(null, 1)}>
                        <i className="fa fa-angle-double-left" aria-hidden="true" />
                    </button>
                </li>
                <li>
                    <button aria-label="Go to previous page"
                            disabled={(props.p === 1 ? true : false)}
                            onClick={props.onUpdate.bind(null, props.p - 1)}>
                        <i className="fa fa-angle-left" aria-hidden="true" />
                    </button>
                </li>
                <li><input
                        value={props.p}
                        type="text"
                        className="form-control"
                        onChange={pageNumChanged}
                        pattern={`[1-${noOfPages}]*`}
                        size={1}/> <span className="text-nowrap">of {noOfPages}</span></li>
                <li>
                    <button aria-label="Go to next page"
                            disabled={(props.p === noOfPages ? true : false)}
                            onClick={props.onUpdate.bind(null, props.p + 1)}>
                        <i className="fa fa-angle-right" aria-hidden="true" />
                    </button>
                </li>
                <li>
                    <button aria-label="Go to last page"
                            disabled={(props.p === noOfPages ? true : false)}
                            onClick={props.onUpdate.bind(null, noOfPages)}>
                        <i className="fa fa-angle-double-right" aria-hidden="true" />
                    </button>
                </li>
            </ul>
        </nav>
    );
}
Pagination.defaultProps = defaultProps;
