"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"

import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination"

export default function PaginationButtons({
  totalPages,
}: {
  totalPages: number
}) {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()
  const currentPage = Number(searchParams.get("page")) || 1

  const createPageURL = (pageNumber: number | string) => {
    const params = new URLSearchParams(searchParams)
    params.set("page", pageNumber.toString())
    router.push(`${pathname}?${params.toString()}`)
    return `${pathname}?${params.toString()}`
  }

  const getPageNumbers = () => {
    let start = Math.max(1, currentPage - 1)
    let end = Math.min(totalPages, currentPage + 1)

    // Always try to show 3 pages if possible
    if (end - start < 2) {
      if (start === 1) {
        end = Math.min(totalPages, start + 2)
      } else if (end === totalPages) {
        start = Math.max(1, end - 2)
      }
    }

    const pages = []
    for (let i = start; i <= end; i++) {
      pages.push(i)
    }
    return pages
  }

  const pageNumbers = getPageNumbers()

  return (
    <div className="mt-4 flex items-center justify-between">
      <div>
        Showing page {currentPage} of {totalPages}
      </div>
      <div>
        <Pagination>
          <PaginationContent>
            {currentPage > 1 && (
              <PaginationItem>
                <PaginationPrevious
                  onClick={() => createPageURL(currentPage - 1)}
                  className="cursor-pointer"
                >
                  Previous
                </PaginationPrevious>
              </PaginationItem>
            )}
            {pageNumbers.map((page) => (
              <PaginationItem key={page}>
                <PaginationLink
                  onClick={() => createPageURL(page)}
                  isActive={page === currentPage}
                  className="cursor-pointer"
                >
                  {page}
                </PaginationLink>
              </PaginationItem>
            ))}
            {currentPage < totalPages && (
              <PaginationItem>
                <PaginationNext
                  onClick={() => createPageURL(currentPage + 1)}
                  className="cursor-pointer"
                >
                  Next
                </PaginationNext>
              </PaginationItem>
            )}
          </PaginationContent>
        </Pagination>
      </div>
    </div>
  )
}
