import { useEffect } from 'react';
import { useControlled, useIsMounted } from '../utils';
import { getPaginationItems } from './helpers';
/** Hook to manage pagination data and state in controlled or uncontrolled way. */
export default function usePagination(props) {
    const { count, defaultPage = 1, onPageChange: onPageChangeProp, page: pageProp, pageSize } = props;
    const [page, onPageChange, { isControlled, reset }] = useControlled({
        defaultValue: defaultPage,
        onChange: onPageChangeProp,
        value: pageProp,
    });
    // In uncontrolled mode, trigger external callback on the first render for consumer to initialize data.
    useEffect(() => {
        !isControlled && onPageChangeProp?.(defaultPage);
    }, []);
    /** In uncontrolled mode, reset pagination whenever pageSize changes (apart from initialization). */
    useEffect(() => {
        isMounted() && reset();
    }, [pageSize]);
    const isMounted = useIsMounted();
    /** How many pages are there in total. */
    const pageCount = count > 0 && pageSize > 0 ? Math.ceil(count / pageSize) : 0;
    /** Array of navigation items, like buttons or arrows. */
    const items = getPaginationItems(page, pageCount);
    /** First item displayed on the current page. */
    const rangeStart = (page - 1) * pageSize + 1;
    /** Last item displayed on the current page. */
    const rangeEnd = page === pageCount ? count : page * pageSize;
    return {
        count,
        items,
        onPageChange,
        page,
        pageCount,
        pageSize,
        rangeEnd,
        rangeStart,
    };
}
//# sourceMappingURL=usePagination.js.map