import {Table as OriTable} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {createPageContext, createSearchContext, usePage, useTableSearch} from '@hooks';
import {PAGE_SIZE_LIST} from '@utils';
import {FC} from 'react';

type Props<T> = {
  testId?: string,
  columns: ColumnsType<T>,
  data: T[],
  pageContext: ReturnType<typeof createPageContext>,
  searchContext: ReturnType<typeof createSearchContext>,
  count: number,
  rowKey?: string,
  'data-testid': string,
  scrollX?: number,
};

const Table: FC<Props<any>> = function<T extends Record<string, any>>(props: Props<T>) {
  const {
    columns,
    data,
    pageContext,
    searchContext,
    count,
    rowKey,
    scrollX,
  } = props;
  const [{page, pageSize}, {onPageChange}] = usePage(pageContext);
  const [isSearching] = useTableSearch(searchContext);

  return (
    <OriTable
      data-testid={props['data-testid']}
      columns={columns}
      dataSource={data}
      pagination={{
        pageSize,
        pageSizeOptions: PAGE_SIZE_LIST,
        total: count,
        showSizeChanger: true,
        onChange: onPageChange,
        current: page,
      }}
      rowKey={rowKey ?? 'id'}
      loading={isSearching}
      scroll={{x: scrollX}}
      bordered
    />
  );
};

export default Table;
