'use client'

import { searchState } from '@/store/boardAtom'
import { useRecoilState, useRecoilValue } from 'recoil'
import { generateBlockPagination } from '@/util/board-utils'

export default function Pagination() {
  const search = useRecoilValue(searchState)

  const [searchForm, setSearchForm] = useRecoilState(searchState)

  const handlePagination = (pageNum) => {
    setSearchForm({ ...searchForm, currentPage: pageNum })
  }

  const totalPages = Math.ceil(search.totalCount / search.pageBlock) > 0 ? Math.ceil(search.totalCount / search.pageBlock) : 1
  const allPages = generateBlockPagination(search.currentPage, totalPages, 10)

  return (
    <>
      <ol className="pagination">
        <li className="page-item first">
          <button
            type="button"
            disabled={search.currentPage === 1}
            onClick={() => {
              handlePagination(1)
            }}
          ></button>
        </li>
        <li className="page-item prev">
          <button
            type="button"
            disabled={search.currentPage <= 1}
            onClick={() => {
              handlePagination(search.currentPage - 1)
            }}
          ></button>
        </li>

        {/* 페이지목록 */}
        {allPages.map((page, index) => {
          return (
            <li className={`page-item ${search.currentPage === page ? 'on' : ''}`} key={index}>
              <button
                type="button"
                onClick={() => {
                  handlePagination(page)
                }}
              >
                {page}
              </button>
            </li>
          )
        })}

        <li className="page-item next">
          <button
            type="button"
            disabled={search.currentPage >= totalPages}
            onClick={() => {
              handlePagination(search.currentPage + 1)
            }}
          ></button>
        </li>
        <li className="page-item last">
          <button
            type="button"
            disabled={search.currentPage === totalPages}
            onClick={() => {
              handlePagination(totalPages)
            }}
          ></button>
        </li>
      </ol>
    </>
  )
}
