/**
 * @file CustomPaginationControls.tsx - Pagination controls component for use with DataTable and FolderTree, or any TanStack Table-enabled component.
 */

import type { Table } from '@tanstack/react-table';
import { type FC, Fragment, useEffect } from 'react';
import { Pagination } from 'react-bootstrap';

/**
 * Props for the CustomPaginationControls component.
 */
interface CustomPaginationControlsProps {
  /** TanStack Table instance to control pagination */
  table: Table<any>;

  /** Total number of pages available */
  totalPages: number;

  /**
   * Whether to use mobile-optimized layout
   *
   * @default false
   */
  isMobile?: boolean;
}

/**
 * Bootstrap-styled pagination controls for TanStack Table.
 *
 * Features:
 * - First/Previous/Next/Last navigation buttons
 * - Intelligent page number display with ellipsis for large page counts
 * - Automatic adjustment when current page exceeds available pages
 * - Responsive layout option for mobile screens
 *
 * @example
 * ```tsx
 * <CustomPaginationControls
 *   table={tableInstance}
 *   totalPages={table.getPageCount()}
 *   isMobile={isSmallScreen}
 * />
 * ```
 */
export const CustomPaginationControls: FC<CustomPaginationControlsProps> = ({
  table,
  totalPages,
  isMobile = false,
}) => {
  // Automatically navigate to the last available page when total pages decreases
  // This prevents being "stuck" on a page that no longer exists
  useEffect(() => {
    const currentIndex = table.getState().pagination.pageIndex;
    if (currentIndex > 0 && currentIndex > totalPages - 1) {
      table.lastPage();
    }
  }, [totalPages]);

  return (
    <Pagination className={`mb-0 ${isMobile ? 'overflow-x-auto' : ''}`}>
      <Pagination.First
        onClick={() => table.firstPage()}
        disabled={!table.getCanPreviousPage()}
      />
      <Pagination.Prev
        onClick={() => table.previousPage()}
        disabled={!table.getCanPreviousPage()}
      />

      {totalPages <= 3 ? (
        // For 3 or fewer pages, show all page numbers
        Array.from({ length: totalPages }).map((_, index) => (
          <Pagination.Item
            key={index}
            active={index === table.getState().pagination.pageIndex}
            onClick={() => table.setPageIndex(index)}
          >
            {index + 1}
          </Pagination.Item>
        ))
      ) : (
        // For more than 3 pages, show first, current neighborhood, and last with ellipsis
        <Fragment>
          {/* Always show first page */}
          <Pagination.Item
            active={0 === table.getState().pagination.pageIndex}
            onClick={() => table.setPageIndex(0)}
          >
            1
          </Pagination.Item>

          {/* Show ellipsis if current page is far from the start */}
          {table.getState().pagination.pageIndex > 2 && (
            <Pagination.Ellipsis disabled />
          )}

          {/* Show current page and adjacent neighbors (excluding first and last) */}
          {[
            table.getState().pagination.pageIndex - 1,
            table.getState().pagination.pageIndex,
            table.getState().pagination.pageIndex + 1,
          ]
            .filter((index) => index > 0 && index < totalPages - 1)
            .map((index) => (
              <Pagination.Item
                key={index}
                active={index === table.getState().pagination.pageIndex}
                onClick={() => table.setPageIndex(index)}
              >
                {index + 1}
              </Pagination.Item>
            ))}

          {/* Show ellipsis if current page is far from the end */}
          {table.getState().pagination.pageIndex < totalPages - 3 && (
            <Pagination.Ellipsis disabled />
          )}

          {/* Always show last page */}
          <Pagination.Item
            active={totalPages - 1 === table.getState().pagination.pageIndex}
            onClick={() => table.setPageIndex(totalPages - 1)}
          >
            {totalPages}
          </Pagination.Item>
        </Fragment>
      )}

      {/* Navigate to next page */}
      <Pagination.Next
        onClick={() => table.nextPage()}
        disabled={!table.getCanNextPage()}
      />

      {/* Navigate to last page */}
      <Pagination.Last
        onClick={() => table.setPageIndex(totalPages - 1)}
        disabled={!table.getCanNextPage()}
      />
    </Pagination>
  );
};
