import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Alert, Card, CardBody, Col, Row, Button, Form } from 'reactstrap';
import Loader from '../common/Loader';
import FalconCardHeader from '../common/FalconCardHeader';
import { isIterableArray } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';

import { useDispatch, useSelector } from 'react-redux';
import { fetchPeople } from '../../store/features/peopleSlice';

import JKPeopleSearch from './JKPeopleSearch';
import JKPeopleList from './JKPeopleList';
import JKPeopleSwiper from './JKPeopleSwiper';
import { useResponsive } from '@farfetch/react-context-responsive';

const JKPeople = ({ className }) => {
  const [showSearch, setShowSearch] = useState(false);
  const [page, setPage] = useState(1);
  const [resetFilter, setResetFilter] = useState(false);
  const peopleListRef = useRef();
  const dispatch = useDispatch();
  const { t } = useTranslation();

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

  const { greaterThan } = useResponsive();

  const loadPeople = React.useCallback(() => {
    if (totalPages !== 0 && page > totalPages) {
      setPage(totalPages + 1);
      return;
    }
    try {
      console.log('BEFORE fetching people');
      dispatch(fetchPeople({ page }));
    } catch (error) {
      console.log('Error fetching people', error);
    }
  }, [page, totalPages, dispatch]);

  useEffect(() => {
    loadPeople();
  }, [page]);

  // useEffect(() => {
  //   if (loadingStatus === 'succeeded' && peopleListRef.current && page !== 1) {
  //   }
  // }, [loadingStatus]);

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

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

  const handleScroll = () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
      goNextPage();
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <Card>
      <JKPeopleSearch
        show={showSearch}
        setShow={setShowSearch}
        resetFilter={resetFilter}
        setResetFilter={setResetFilter}
      />
      <FalconCardHeader title={t('page_title', { ns: 'people' })} titleClass="font-weight-bold">
        <Form inline className="mt-md-0 mt-3">
          <Button
            color="primary"
            className="me-2 mr-2 fs--1"
            onClick={() => setShowSearch(!showSearch)}
            data-testid="btnUpdateSearch"
          >
            {t('update_search', { ns: 'people' })}
          </Button>
          <Button
            outline
            color="secondary"
            className="fs--1"
            data-testid="btnResetSearch"
            onClick={() => setResetFilter(true)}
          >
            {t('reset_filters', { ns: 'people' })}
          </Button>
        </Form>
      </FalconCardHeader>

      <CardBody className="pt-0">
        {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} />
                  {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>
        )}
      </CardBody>
    </Card>
  );
};

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

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

export default JKPeople;
