import { Fragment } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Fetcher from './fetcher';
import Pagination from '../pagination';
import Error from '../error';
import useQueryParams from '../../../hooks/query-params';

function PaginatedFetcher(props) {
  const page = parseInt(useQueryParams().get('page')) || 1;
  return (
    <Fetcher action={props.action.bind(null, page)} stateSelector={props.stateSelector}>
      {data => (
        <Fragment>
          {props.children(data)}
          <Pagination page={page} pageCount={props.pageCount} />
        </Fragment>
      )}
    </Fetcher>
  );
}

PaginatedFetcher.propTypes = {
  action: PropTypes.func.isRequired,
  stateSelector: PropTypes.func.isRequired,
  pageCount: PropTypes.number.isRequired,
  renderEmpty: PropTypes.func.isRequired,
  renderError: PropTypes.func.isRequired
};

PaginatedFetcher.defaultProps = {
  renderEmpty: () => null,
  renderError: () => <Error />
};

function mapStateToProps(state, { stateSelector }) {
  return { pageCount: stateSelector(state).pageCount };
}

export default connect(mapStateToProps)(PaginatedFetcher);
