import React, {useState, useRef, useEffect}  from 'react'
import { connect } from 'react-redux'
import InfiniteScroll from "react-infinite-scroll-component"
import {fetchEducatorListAsync, clearGetEducatorListState } from '../../../../redux/dashboard/educator-list/educator-list.action'
import {getEducatorList, getEducatorListFetchInProgress, getEducatorListFetchingErrorMessages, getEducatorListCount} from './selectors'

const EducatorListInPopover = ({
    educators, totalItems,loading, itemRow, itemClickHandler = ()=>{},
    doFetchEducatorList, doClearList
}) => {
    
    const [page, setPage] = useState(1)
    const [items, setItems] = useState([])
    const [hasMore, setHasMore] = useState(true)



    const style = {
        height: 30,
        border: "1px solid lightgrey",
        margin: 6,
        padding: 8,
        width: 150
      };

    useEffect(() =>{
        if(!loading){
            doFetchEducatorList()
            console.log(`🦋 ${itemRow}`)
            // console.log("fetching ..")
        }
        return () => {
            doClearList()
            // console.log('ending...')
          }
    },[])

    useEffect(() => {
        if(items.length < totalItems)
            setItems(items.concat(educators))
    }, [educators])
    
    const fetchMoreData = () => {
        if (items.length >= totalItems) {
            setHasMore(false)
            return
        }

        // setItems(items.concat(educators))
        doFetchEducatorList(page + 1)
        // console.log("fetching ...")
        setPage(page + 1)
    }

    return (            
            <InfiniteScroll
                className="scroll-bound"
                dataLength={items.length}
                next={fetchMoreData}
                hasMore={hasMore}
                loader={<h6>Loading...</h6>}
                height={150}                            
                endMessage={
                    <p style={{ textAlign: "center" }}>
                    <b>Yay! You have seen it all</b>
                    </p>
                }
                >
                {items.map((item, index) => (
                    <div style={style} key={index} onClick={e => itemClickHandler(itemRow, e, item.UserId)}>
                    {item.FirstName} {item.LastName}
                    </div>
                ))}
            </InfiniteScroll>
      )
}

  const mapStateToProps = state => ({
    educators: getEducatorList(state),
    loading: getEducatorListFetchInProgress(state),
    errorMessage: getEducatorListFetchingErrorMessages(state),
    totalItems: getEducatorListCount(state),
})

const mapDispatchToProps = dispatch => ({
    doFetchEducatorList: (page=1) => dispatch(fetchEducatorListAsync(page)),
    doClearList:() => dispatch(clearGetEducatorListState())
})

export default connect(mapStateToProps, mapDispatchToProps)(EducatorListInPopover)