import { useState } from "react"

export const usePagination = (totalRecords: number, initialPerPage = 10) => {
  const [currentPage, setCurrentPage] = useState(1)
  const [recordsPerPage, setRecordsPerPage] = useState(initialPerPage)
  const totalPages = Math.ceil(totalRecords / recordsPerPage)
  const startIndex = (currentPage - 1) * recordsPerPage
  const endIndex = Math.min(startIndex + recordsPerPage, totalRecords)

  const handlePreviousPage = () => {
    if (currentPage > 1) {
      setCurrentPage((prev) => prev - 1)
    }
  }

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage((prev) => prev + 1)
    }
  }

  const handleRecordsPerPageChange = (value: number) => {
    setRecordsPerPage(value)
    setCurrentPage(1) 
  }

  return {
    currentPage,
    recordsPerPage,
    totalPages,
    startIndex,
    endIndex,
    setCurrentPage,
    setRecordsPerPage,
    handlePreviousPage,
    handleNextPage,
    handleRecordsPerPageChange
  }
}
