import { useEffect, useState } from 'react';

const getStartIndex = (itemsPerPage, currentPage) => itemsPerPage * (currentPage - 1);
const getEndIndex = (itemsPerPage, currentPage) => itemsPerPage * currentPage;

// usage on data rows.slice(startIndex, endIndex)
const useLocalPagination = (itemsPerPage, currentPage = 1) => {
  const [currentPage$, setCurrentPage] = useState(currentPage);
  const [itemsPerPage$, setItemsPerPage] = useState(itemsPerPage);
  const [startIndex$, setStartIndex] = useState(getStartIndex(itemsPerPage, currentPage));
  const [endIndex$, setEndIndex] = useState(getEndIndex(itemsPerPage, currentPage));

  useEffect(() => {
    setStartIndex(getStartIndex(itemsPerPage$, currentPage$));
    setEndIndex(getEndIndex(itemsPerPage$, currentPage$));
  }, [itemsPerPage$, currentPage$]);

  return {
    startIndex: startIndex$,
    endIndex: endIndex$,
    currentPage: currentPage$,
    itemsPerPage: itemsPerPage$,
    setCurrentPage,
    setItemsPerPage,
  };
};

export default useLocalPagination;
