"use client"

import type { Table as TanstackTable } from "@tanstack/react-table"

import { PageSizeSelect, PageStepButtons } from "@/components/ui/pagination-controls"

type TablePagerProps<T> = {
  table: TanstackTable<T>
  /** Unique id for the page-size select, so several tables can share a page. */
  pageSizeId: string
}

const PAGE_SIZES = [10, 20, 50] as const

/**
 * Rows-per-page select plus first/prev/next/last buttons for a client-side
 * TanStack table. Callers own the surrounding layout (alignment, row count text).
 */
export function TablePager<T>({ table, pageSizeId }: TablePagerProps<T>) {
  const { pageIndex, pageSize } = table.getState().pagination

  return (
    <div className="flex flex-wrap items-center gap-4">
      <PageSizeSelect
        id={pageSizeId}
        value={pageSize}
        options={PAGE_SIZES}
        onValueChange={(size) => table.setPageSize(size)}
      />
      <PageStepButtons
        canPrevious={table.getCanPreviousPage()}
        canNext={table.getCanNextPage()}
        onFirst={() => table.setPageIndex(0)}
        onPrevious={() => table.previousPage()}
        onNext={() => table.nextPage()}
        onLast={() => table.setPageIndex(table.getPageCount() - 1)}
      >
        <span className="min-w-[100px] text-center text-sm">
          Page {pageIndex + 1} of {table.getPageCount() || 1}
        </span>
      </PageStepButtons>
    </div>
  )
}
