"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = usePagination;
const react_1 = require("react");
const utils_1 = require("../utils");
const helpers_1 = require("./helpers");
/** Hook to manage pagination data and state in controlled or uncontrolled way. */
function usePagination(props) {
    const { count, defaultPage = 1, onPageChange: onPageChangeProp, page: pageProp, pageSize } = props;
    const [page, onPageChange, { isControlled, reset }] = (0, utils_1.useControlled)({
        defaultValue: defaultPage,
        onChange: onPageChangeProp,
        value: pageProp,
    });
    // In uncontrolled mode, trigger external callback on the first render for consumer to initialize data.
    (0, react_1.useEffect)(() => {
        !isControlled && (onPageChangeProp === null || onPageChangeProp === void 0 ? void 0 : onPageChangeProp(defaultPage));
    }, []);
    /** In uncontrolled mode, reset pagination whenever pageSize changes (apart from initialization). */
    (0, react_1.useEffect)(() => {
        isMounted() && reset();
    }, [pageSize]);
    const isMounted = (0, utils_1.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 = (0, helpers_1.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