import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Alert, Col, Row } from 'reactstrap';
import Loader from '../common/Loader';
import { isIterableArray } from '../../helpers/utils';
import { useSelector } from 'react-redux';
import JKPeopleList from './JKPeopleList';
import JKPeopleSwiper from './JKPeopleSwiper';
import { useResponsive } from '@farfetch/react-context-responsive';

const JKPeople = ({ className, onPageChange }) => {
  
  const [page, setPage] = useState(1);
  const [hasNext, setHasNext] =  useState(false)
  const peopleListRef = useRef();

  const people = useSelector(state => state.people.people);
  const totalPages = useSelector(state => state.people.totalPages);
  const loadingStatus = useSelector(state => state.people.status);

  const { greaterThan } = useResponsive();

  useEffect(() => {
    try {
      onPageChange(page, hasNext)
    } catch (error) {
      console.log('Error fetching people', error);
    }

  }, [page]);

  useEffect(() => {
    setHasNext(page < totalPages)
  }, [totalPages, page])

  const goNextPage = () => {
    setPage(val => ++val);
  };

  const goPrevPage = () => {
    if (page > 1) {
      setPage(prev => --prev);
    }
  };

  return (
    <div>
      {loadingStatus === 'loading' && people.length === 0 ? (
        <Loader />
      ) : isIterableArray(people) ? (
        //Start Find Friends table hidden on small screens
        <>
          {greaterThan.xs ? (
            <Row className="mb-3 justify-content-between d-none d-md-block">
              <div className="table-responsive-xl px-2" ref={peopleListRef}>
                <JKPeopleList people={people} goNextPage={goNextPage} hasNext={hasNext} />
                {loadingStatus === 'loading' && people.length !== 0 && <span>loading...</span>}
              </div>
            </Row>
          ) : (
            <Row className="swiper-container d-block d-md-none" data-testid="peopleSwiper">
              <JKPeopleSwiper people={people} goNextPage={goNextPage} />
            </Row>
          )}
        </>
      ) : (
        <Row className="p-card">
          <Col>
            <Alert color="info" className="mb-0">
              No Records!
            </Alert>
          </Col>
        </Row>
      )}
    </div>
  );
};

JKPeople.propTypes = {
  className: PropTypes.string
};

JKPeople.defaultProps = {
  className: 'col-6 col-md-4 col-lg-3 col-xxl-2'
};

export default JKPeople;
