import { useState, useMemo } from 'react'; interface UsePaginationProps { initialPage?: number; initialItemsPerPage?: number; } interface UsePaginationReturn { currentPage: number; itemsPerPage: number; totalPages: number; paginatedData: T[]; setCurrentPage: (page: number) => void; setItemsPerPage: (itemsPerPage: number) => void; resetPagination: () => void; } export function usePagination( data: T[], { initialPage = 1, initialItemsPerPage = 25 }: UsePaginationProps = {} ): UsePaginationReturn { const [currentPage, setCurrentPage] = useState(initialPage); const [itemsPerPage, setItemsPerPage] = useState(initialItemsPerPage); const totalPages = Math.ceil(data.length / itemsPerPage); const paginatedData = useMemo(() => { const startIndex = (currentPage - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; return data.slice(startIndex, endIndex); }, [data, currentPage, itemsPerPage]); const handleSetCurrentPage = (page: number) => { const validPage = Math.max(1, Math.min(page, totalPages)); setCurrentPage(validPage); }; const handleSetItemsPerPage = (newItemsPerPage: number) => { setItemsPerPage(newItemsPerPage); // Reset to first page when changing items per page setCurrentPage(1); }; const resetPagination = () => { setCurrentPage(initialPage); setItemsPerPage(initialItemsPerPage); }; // Auto-adjust current page if it exceeds total pages if (currentPage > totalPages && totalPages > 0) { setCurrentPage(totalPages); } return { currentPage, itemsPerPage, totalPages, paginatedData, setCurrentPage: handleSetCurrentPage, setItemsPerPage: handleSetItemsPerPage, resetPagination, }; }