import type { Table } from '@tanstack/react-table'
import { Pagination } from '../Pagination'

export function TablePagination<TData>({
  table,
  pageControlMode = 'select',
  showPaginationDisplay = true,
  isLoading = false,
}: {
  table: Table<TData>
  pageControlMode?: 'select' | 'display'
  showPaginationDisplay?: boolean
  isLoading?: boolean
}) {
  if (!table) return null
  if (!table.initialState?.pagination) return null

  const isServerSide = table.options.manualPagination
  const meta = (table.options.meta as any) ?? {}
  const totalCount = isServerSide
    ? meta.totalCount
    : table.getPrePaginationRowModel().rows.length
  const currentPageCount = isServerSide
    ? (meta.currentPageCount ?? table.getRowModel().rows.length)
    : table.getRowModel().rows.length
  const canNextPage = isServerSide
    ? (meta.canNextPage ?? table.getCanNextPage())
    : table.getCanNextPage()

  const paginationProps = {
    pageIndex: table.getState().pagination.pageIndex,
    pageSize: table.getState().pagination.pageSize,
    totalCount,
    currentPageCount,
    canNextPage,
    isLoading,
    onPageChange: (pageIndex: number) => table.setPageIndex(pageIndex),
    pageControlMode,
    showPaginationDisplay,
  }

  return <Pagination {...paginationProps} />
}
