import * as React from "react";

export function usePagination(
  count: number = 1,
  initialPageSize: number = 25,
  intialPage: number = 1,
) {
  const [pageSize, _setPageSize] = React.useState(initialPageSize);
  const [currentPage, setCurrentPage] = React.useState(intialPage);
  const totalPages = Math.ceil(count / pageSize);
  const hasPrevious = currentPage > 1;
  const hasNext = currentPage < totalPages;
  const after = (currentPage - 1) * pageSize;

  const nextPage = React.useCallback(() => {
    if (hasNext) {
      setCurrentPage((page) => page + 1);
    }
  }, [hasNext]);

  const previousPage = React.useCallback(() => {
    if (hasPrevious) {
      setCurrentPage((page) => page - 1);
    }
  }, [hasPrevious]);

  const setPageSize = React.useCallback((page: number) => {
    _setPageSize(page);
    setCurrentPage(1);
  }, []);

  return {
    pageSize,
    after,
    currentPage,
    setCurrentPage,
    setPageSize,
    totalPages,
    hasPrevious,
    hasNext,
    nextPage,
    previousPage,
  };
}
