"use client";

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

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

type Props<T> = {
  table: Table<T>;
  totalRows: number;
  itemNoun: string;
  /** Pluralized form (defaults to itemNoun + "s") */
  itemNounPlural?: string;
  pageSizes?: number[];
  /** Stable id prefix to avoid collisions when multiple tables share a page. */
  idPrefix?: string;
};

export function DataTablePagination<T>({
  table,
  totalRows,
  itemNoun,
  itemNounPlural,
  pageSizes = [...PAGE_SIZE_OPTIONS],
  idPrefix = "data-table",
}: Props<T>) {
  const noun = totalRows === 1 ? itemNoun : (itemNounPlural ?? `${itemNoun}s`);
  const pageSizeId = `${idPrefix}-page-size`;

  return (
    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
      <p className="text-muted-foreground text-sm">
        {totalRows} {noun}
      </p>
      <div className="flex w-full flex-wrap items-center justify-end gap-4 sm:w-auto">
        <PageSizeSelect
          id={pageSizeId}
          value={table.getState().pagination.pageSize}
          options={pageSizes}
          onValueChange={(size) => table.setPageSize(size)}
          labelClassName="font-medium text-sm whitespace-nowrap"
          triggerSize="sm"
          triggerClassName="w-20"
          contentSide="top"
          grouped
        />
        <div className="font-medium text-sm tabular-nums">
          Page {table.getState().pagination.pageIndex + 1} of {Math.max(table.getPageCount(), 1)}
        </div>
        <PageStepButtons
          canPrevious={table.getCanPreviousPage()}
          canNext={table.getCanNextPage()}
          onFirst={() => table.setPageIndex(0)}
          onPrevious={() => table.previousPage()}
          onNext={() => table.nextPage()}
          onLast={() => table.setPageIndex(table.getPageCount() - 1)}
        />
      </div>
    </div>
  );
}
