import { type FC } from 'react';
import { Controller } from 'react-hook-form';

import { TablePagination } from '@mui/material';

import { type FormValues } from '../../../../hooks/useServerPagination';

import { type PaginationControllerProps } from './types';

const PaginationController: FC<
  PaginationControllerProps<FormValues>
> = props => {
  const {
    control,
    total,
    setPage,
    setLimit,
    limitOptions,
    labelRowsPerPage = '',
  } = props;

  return (
    <Controller
      control={control}
      name="pagination"
      render={({ field }) => (
        <TablePagination
          {...field}
          component="div"
          count={total}
          onPageChange={(event, page) => setPage(page)}
          onRowsPerPageChange={event =>
            setLimit(parseInt(event.target.value, 10))
          }
          labelRowsPerPage={labelRowsPerPage}
          page={field.value.page}
          rowsPerPage={field.value.limit}
          rowsPerPageOptions={limitOptions}
        />
      )}
    />
  );
};

export default PaginationController;
