import { useEffect, useState } from 'react';
import { Route, useRouteMatch } from 'react-router-dom';
import { connect } from 'react-redux';

import s from './Goods.module.css';
import { asyncGetGoods } from '../../redux/goods/operation';
import { IGoodsProps, IGoodsState } from '../../typescript/goods/interfaces';
import { TRouteMatchName } from '../../typescript/goods/types';

import Good from './Good/Good';
import Pagination from '../PaginationBar/PaginationBar';

const Goods = ({ goodsArr, getGoods }: IGoodsProps) => {
  const {
    params: { name: routName },
  }: TRouteMatchName = useRouteMatch();

  useEffect(() => {
    getGoods();
  }, [getGoods]);

  const [page, setPage] = useState<number>(1);
  const handlePageChange = (page: number) => setPage(page);

  return goodsArr ? (
    <Route>
      <ul className={s.goods_list}>
        {goodsArr.length !== 0 &&
          goodsArr
            .slice((page - 1) * 5, page * 5)
            .map((good: any, i: number) => (
              <Good key={i} good={good} routName={routName} />
            ))}
      </ul>
      <Pagination
        page={page}
        total={Math.ceil(goodsArr.length / 5)}
        handlePageChange={handlePageChange}
      />
    </Route>
  ) : null;
};

const mapStateToProps = (state: IGoodsState) => ({
  goodsArr: state.goods.goodsArr,
});

const mapDispatchToProps = (dispatch: any) => ({
  getGoods: () => dispatch(asyncGetGoods()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Goods);
