import { PaginationEllipsis, PaginationItem, PaginationLink } from "@/components/ui/pagination";

export const generatePaginationLinks = (
  currentPage: number,
  totalPages: number,
  onPageChange: (page: number) => void
) => {
  const pages: JSX.Element[] = [];
  
  // Show all pages if total pages is 6 or less
  if (totalPages <= 6) {
    for (let i = 1; i <= totalPages; i++) {
      pages.push(
        <PaginationItem key={i}>
          <PaginationLink
            onClick={() => onPageChange(i)}
            isActive={i === currentPage}
            className="cursor-pointer"
          >
            {i}
          </PaginationLink>
        </PaginationItem>
      );
    }
    return pages;
  }

  // Always show first page
  pages.push(
    <PaginationItem key={1}>
      <PaginationLink
        onClick={() => onPageChange(1)}
        isActive={1 === currentPage}
        className="cursor-pointer"
      >
        1
      </PaginationLink>
    </PaginationItem>
  );

  // Calculate range for middle section
  let startPage = Math.max(2, currentPage - 1);
  let endPage = Math.min(totalPages - 1, currentPage + 1);

  // Show ellipsis after first page if needed
  if (startPage > 2) {
    if (startPage > 3) {
      pages.push(<PaginationEllipsis key="ellipsis-1" />);
    }
    // Show page 2 if we're not starting from it
    if (startPage > 2) {
      pages.push(
        <PaginationItem key={2}>
          <PaginationLink
            onClick={() => onPageChange(2)}
            isActive={2 === currentPage}
            className="cursor-pointer"
          >
            2
          </PaginationLink>
        </PaginationItem>
      );
    }
  }

  // Add middle pages
  for (let i = startPage; i <= endPage; i++) {
    pages.push(
      <PaginationItem key={i}>
        <PaginationLink
          onClick={() => onPageChange(i)}
          isActive={i === currentPage}
          className="cursor-pointer"
        >
          {i}
        </PaginationLink>
      </PaginationItem>
    );
  }

  // Show ellipsis before last page if needed
  if (endPage < totalPages - 1) {
    // Show second to last page if we're not ending on it
    if (endPage < totalPages - 2) {
      pages.push(
        <PaginationItem key={totalPages - 1}>
          <PaginationLink
            onClick={() => onPageChange(totalPages - 1)}
            isActive={totalPages - 1 === currentPage}
            className="cursor-pointer"
          >
            {totalPages - 1}
          </PaginationLink>
        </PaginationItem>
      );
    }
    if (endPage < totalPages - 2) {
      pages.push(<PaginationEllipsis key="ellipsis-2" />);
    }
  }

  // Always show last page
  pages.push(
    <PaginationItem key={totalPages}>
      <PaginationLink
        onClick={() => onPageChange(totalPages)}
        isActive={totalPages === currentPage}
        className="cursor-pointer"
      >
        {totalPages}
      </PaginationLink>
    </PaginationItem>
  );

  return pages;
};