import { Pagination, Select } from '@douyinfe/semi-ui';
import { useId, type ReactNode } from 'react';

type PageSizeOption = {
  value: number;
  label: string;
};

type TablePaginationProps = {
  page: number;
  totalPages: number;
  info: ReactNode;
  onPageChange: (page: number) => void;
  disabled?: boolean;
  pageSize?: number;
  pageSizeOptions?: PageSizeOption[];
  pageSizeLabel?: string;
  onPageSizeChange?: (pageSize: number) => void;
};

export function TablePagination({
  page,
  totalPages,
  info,
  onPageChange,
  disabled = false,
  pageSize,
  pageSizeOptions,
  pageSizeLabel = '每页数量',
  onPageSizeChange
}: TablePaginationProps) {
  const safeTotalPages = Math.max(1, totalPages);
  const safePage = Math.min(Math.max(1, page), safeTotalPages);
  const pageSizeID = `v2-page-size-${useId().replace(/:/g, '')}`;

  return <>
    <span className="v2-table-pagination-info">{info}</span>
    <div className="v2-table-pagination-controls">
      <Pagination
        className="v2-table-pagination"
        size="small"
        currentPage={safePage}
        total={safeTotalPages}
        pageSize={1}
        disabled={disabled}
        hideOnSinglePage={false}
        hoverShowPageSelect={!disabled}
        onPageChange={onPageChange}
      />
      {pageSize != null && pageSizeOptions?.length && onPageSizeChange ? <>
        <span className="v2-sr-only" id={pageSizeID}>{pageSizeLabel}</span>
        <Select
          className="v2-table-pagination-size"
          aria-labelledby={pageSizeID}
          disabled={disabled}
          value={pageSize}
          onChange={(value) => onPageSizeChange(Number(value))}
          optionList={pageSizeOptions}
        />
      </> : null}
    </div>
  </>;
}
