"use client";

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

type Props = {
  currentPage: number;
  totalPages: number;
  onChange: (page: number) => void;
};

export default function PaginationLite({
  currentPage,
  totalPages,
  onChange,
}: Props) {
  const getPages = () => {
    const visibleCount = 7; // maximum number of items to show (including ellipses)
    const pages: (number | string)[] = [];

    // If total pages are within visible limit, show all
    if (totalPages <= visibleCount) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
      return pages;
    }

    // If current page is near the beginning: show 1..5, ellipsis, last
    if (currentPage <= 4) {
      for (let i = 1; i <= 5; i++) pages.push(i);
      pages.push("…", totalPages);
      return pages;
    }

    // If current page is near the end: show first, ellipsis, last-4..last
    if (currentPage >= totalPages - 3) {
      pages.push(1, "…");
      for (let i = totalPages - 4; i <= totalPages; i++) pages.push(i);
      return pages;
    }

    // Middle case: first, ellipsis, current-1, current, current+1, ellipsis, last
    pages.push(
      1,
      "…",
      currentPage - 1,
      currentPage,
      currentPage + 1,
      "…",
      totalPages,
    );
    return pages;
  };

  const pages = getPages();

  return (
    <Pagination className="w-full flex justify-center items-center mx-auto">
      <PaginationContent className="w-full px-auto items-center flex justify-center ">
        {totalPages !== 1 && (
          <PaginationPrevious
            className="hover:cursor-pointer text-white hover:text-white"
            onClick={() => onChange(Math.max(1, currentPage - 1))}
          />
        )}

        {/* Pages */}
        {pages.map((p, idx) =>
          p === "…" ? (
            <PaginationItem key={idx} className="px-2 text-white">
              …
            </PaginationItem>
          ) : (
            <PaginationItem key={idx}>
              <PaginationLink
                className="hover:cursor-pointer text-white hover:text-white"
                isActive={p === currentPage}
                onClick={() => onChange(Number(p))}
              >
                {p}
              </PaginationLink>
            </PaginationItem>
          ),
        )}
        {totalPages !== 1 && (
          <PaginationNext
            className="hover:cursor-pointer text-white hover:text-white"
            onClick={() => onChange(Math.min(totalPages, currentPage + 1))}
          />
        )}
      </PaginationContent>
    </Pagination>
  );
}
