'use client' import { useState, useCallback, useMemo } from 'react' import { UsePaginationReturn } from '../types' interface UsePaginationProps { totalCount: number initialPageSize?: number initialPage?: number serverSide?: boolean onPageChange?: (page: number) => void } export function usePagination({ totalCount, initialPageSize = 25, initialPage = 1, serverSide = false, onPageChange, }: UsePaginationProps): UsePaginationReturn { const [currentPage, setCurrentPage] = useState(initialPage) const [pageSize, setPageSize] = useState(initialPageSize) const totalPages = useMemo(() => { return Math.max(1, Math.ceil(totalCount / pageSize)) }, [totalCount, pageSize]) const canGoNext = useMemo(() => { return currentPage < totalPages }, [currentPage, totalPages]) const canGoPrevious = useMemo(() => { return currentPage > 1 }, [currentPage]) const goToPage = useCallback((page: number) => { const validPage = Math.max(1, Math.min(page, totalPages)) setCurrentPage(validPage) onPageChange?.(validPage) }, [totalPages, onPageChange]) const goToFirstPage = useCallback(() => { goToPage(1) }, [goToPage]) const goToLastPage = useCallback(() => { goToPage(totalPages) }, [goToPage, totalPages]) const goToNextPage = useCallback(() => { if (canGoNext) { goToPage(currentPage + 1) } }, [canGoNext, currentPage, goToPage]) const goToPreviousPage = useCallback(() => { if (canGoPrevious) { goToPage(currentPage - 1) } }, [canGoPrevious, currentPage, goToPage]) const getPageNumbers = useCallback((): (number | '...')[] => { const maxVisible = 7 // Maximum number of page buttons to show if (totalPages <= maxVisible) { // Show all pages if total is small return Array.from({ length: totalPages }, (_, i) => i + 1) } const pages: (number | '...')[] = [] // Always show first page pages.push(1) if (currentPage > 3) { pages.push('...') } // Show pages around current const start = Math.max(2, currentPage - 1) const end = Math.min(totalPages - 1, currentPage + 1) for (let i = start; i <= end; i++) { if (!pages.includes(i)) { pages.push(i) } } if (currentPage < totalPages - 2) { pages.push('...') } // Always show last page if (!pages.includes(totalPages)) { pages.push(totalPages) } return pages }, [currentPage, totalPages]) const getDisplayRange = useCallback(() => { const start = (currentPage - 1) * pageSize + 1 const end = Math.min(currentPage * pageSize, totalCount) return { start, end } }, [currentPage, pageSize, totalCount]) return { currentPage, pageSize, totalPages, totalCount, canGoNext, canGoPrevious, goToPage, goToFirstPage, goToLastPage, goToNextPage, goToPreviousPage, getPageNumbers, getDisplayRange, } }