import usePagination from '@/hooks/usePagination'

export default function QPagination(props) {
  const { handleChangePage = () => {}, pagePerBlock = 10 } = props
  const { currentPage, changePage, pageGroup, totalPages, pages, startPage, endPage, pageRange } = usePagination(props)

  const handlePage = (page) => {
    handleChangePage(page)
    changePage(page)
  }

  return (
    <ol className="pagination">
      <li className="page-item first">
        <button type="button" disabled={currentPage === 1} onClick={() => handlePage(1)}></button>
      </li>
      <li className="page-item prev">
        <button
          type="button"
          disabled={currentPage <= 1}
          onClick={() => {
            if (currentPage === 1) return
            handlePage(Math.max(1, (pageGroup - 2) * pagePerBlock + 1))
          }}
        ></button>
      </li>
      {pageRange.map((page) => (
        <li className={page === currentPage ? `page-item on` : `page-item`} key={page}>
          <button type="button" onClick={() => handlePage(page)} disabled={pageRange.length === 1}>
            {page}
          </button>
        </li>
      ))}
      <li className="page-item next">
        <button
          type="button"
          disabled={currentPage >= totalPages}
          onClick={() => {
            if (currentPage === totalPages) return
            if (pageGroup * pagePerBlock + 1 <= totalPages) handlePage(Math.max(1, pageGroup * pagePerBlock + 1))
          }}
        ></button>
      </li>
      <li className="page-item last">
        <button type="button" disabled={totalPages === 0 ? true : currentPage === totalPages} onClick={() => handlePage(totalPages)}></button>
      </li>
    </ol>
  )
}
