import type { PaginationItem } from '../components/EmployeesPagination/EmployeesPagination'

export function getPaginationItems(
  currentPage: number,
  totalPages: number,
): PaginationItem[] {
  if (totalPages <= 0) return []

  const current = currentPage + 1

  if (totalPages <= 7) {
    return Array.from({ length: totalPages }, (_, index) => index + 1)
  }

  const pages = new Set<number>()

  pages.add(1)
  pages.add(totalPages)
  pages.add(current)
  pages.add(current - 1)
  pages.add(current + 1)

  if (current <= 4) {
    pages.add(2)
    pages.add(3)
    pages.add(4)
    pages.add(5)
  }

  if (current >= totalPages - 3) {
    pages.add(totalPages - 1)
    pages.add(totalPages - 2)
    pages.add(totalPages - 3)
    pages.add(totalPages - 4)
  }

  const sortedPages = Array.from(pages)
    .filter((page) => page >= 1 && page <= totalPages)
    .sort((a, b) => a - b)

  const result: PaginationItem[] = []

  sortedPages.forEach((page, index) => {
    const previousPage = sortedPages[index - 1]

    if (previousPage && page - previousPage > 1) {
      if (page - previousPage === 2) {
        result.push(previousPage + 1)
      } else {
        result.push(page < current ? 'prev-ellipsis' : 'next-ellipsis')
      }
    }

    result.push(page)
  })

  return result
}