'use client';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { useSearchParams } from "next/navigation";
import { useCallback, useMemo } from "react";

export default function CustomPagination({ totalNumberOfPages = 1 }) {
  const searchParams = useSearchParams();

  // Get current page from search params, default to 1 if not present or invalid
  const currentPage = useMemo(() => {
    const page = Number(searchParams.get("page")) || 1;
    return page < 1 ? 1 : page > totalNumberOfPages ? totalNumberOfPages : page;
  }, [searchParams, totalNumberOfPages]);

  // Create a URL with updated page parameter
  const createPageURL = useCallback(
    (pageNumber) => {
      const params = new URLSearchParams(searchParams.toString());
      params.set("page", pageNumber.toString());
      return `?${params.toString()}`;
    },
    [searchParams]
  );

  // Generate visible page numbers
  const visiblePageNumbers = useMemo(() => {
    // Maximum number of page buttons to show (excluding ellipsis, prev, next)
    const maxVisiblePages = 3;

    if (totalNumberOfPages <= maxVisiblePages) {
      // If we have few pages, show all of them
      return Array.from({ length: totalNumberOfPages }, (_, i) => i + 1);
    }

    // We need to determine which pages to show with ellipsis
    let startPage;
    let endPage;

    if (currentPage <= Math.ceil(maxVisiblePages / 2)) {
      // User is near the beginning
      startPage = 1;
      endPage = maxVisiblePages;
      return {
        start: Array.from({ length: endPage }, (_, i) => i + 1),
        showEndEllipsis: true,
        end: [totalNumberOfPages],
      };
    } else if (
      currentPage >=
      totalNumberOfPages - Math.floor(maxVisiblePages / 2)
    ) {
      // User is near the end
      startPage = totalNumberOfPages - maxVisiblePages + 1;
      endPage = totalNumberOfPages;
      return {
        start: [1],
        showStartEllipsis: true,
        end: Array.from(
          { length: endPage - startPage + 1 },
          (_, i) => startPage + i
        ),
      };
    } else {
      // User is in the middle
      startPage = currentPage - 1;
      endPage = currentPage + 1;
      return {
        start: [1],
        showStartEllipsis: true,
        middle: Array.from(
          { length: endPage - startPage + 1 },
          (_, i) => startPage + i
        ),
        showEndEllipsis: true,
        end: [totalNumberOfPages],
      };
    }
  }, [currentPage, totalNumberOfPages]);

  const isActivePage = useCallback(
    (pageNumber) => {
      return pageNumber === currentPage;
    },
    [currentPage]
  );

  // If there's only one page, don't render pagination
  if (totalNumberOfPages <= 1) {
    return null;
  }

  return (
    <Pagination dir="ltr">
      <PaginationContent>
        <PaginationItem>
          <PaginationPrevious
            href={createPageURL(currentPage - 1)}
            className={currentPage <= 1 ? "pointer-events-none opacity-50" : ""}
          />
        </PaginationItem>

        {/* Render page numbers based on the calculated visible page numbers */}
        {Array.isArray(visiblePageNumbers) ? (
          // Simple case: all page numbers are shown
          visiblePageNumbers.map((pageNum) => (
            <PaginationItem key={pageNum}>
              <PaginationLink
                href={createPageURL(pageNum)}
                isActive={isActivePage(pageNum)}
              >
                {pageNum}
              </PaginationLink>
            </PaginationItem>
          ))
        ) : (
          // Complex case with ellipsis
          <>
            {/* Start pages */}
            {visiblePageNumbers.start &&
              visiblePageNumbers.start.map((pageNum) => (
                <PaginationItem key={`start-${pageNum}`}>
                  <PaginationLink
                    href={createPageURL(pageNum)}
                    isActive={isActivePage(pageNum)}
                  >
                    {pageNum}
                  </PaginationLink>
                </PaginationItem>
              ))}

            {/* Start ellipsis */}
            {visiblePageNumbers.showStartEllipsis && (
              <PaginationItem>
                <PaginationEllipsis />
              </PaginationItem>
            )}

            {/* Middle pages */}
            {visiblePageNumbers.middle &&
              visiblePageNumbers.middle.map((pageNum) => (
                <PaginationItem key={`middle-${pageNum}`}>
                  <PaginationLink
                    href={createPageURL(pageNum)}
                    isActive={isActivePage(pageNum)}
                  >
                    {pageNum}
                  </PaginationLink>
                </PaginationItem>
              ))}

            {/* End ellipsis */}
            {visiblePageNumbers.showEndEllipsis && (
              <PaginationItem>
                <PaginationEllipsis />
              </PaginationItem>
            )}

            {/* End pages */}
            {visiblePageNumbers.end &&
              visiblePageNumbers.end.map((pageNum) => (
                <PaginationItem key={`end-${pageNum}`}>
                  <PaginationLink
                    href={createPageURL(pageNum)}
                    isActive={isActivePage(pageNum)}
                  >
                    {pageNum}
                  </PaginationLink>
                </PaginationItem>
              ))}
          </>
        )}

        <PaginationItem>
          <PaginationNext
            href={createPageURL(currentPage + 1)}
            className={
              currentPage >= totalNumberOfPages
                ? "pointer-events-none opacity-50"
                : ""
            }
          />
        </PaginationItem>
      </PaginationContent>
    </Pagination>
  );
}
