import React, { useEffect, useState } from 'react';
import { connect, useDispatch, useSelector } from 'react-redux';

import { Box, Divider, Paper } from '@mui/material';
import { styled } from '@mui/material/styles';
import { Container } from '@mui/system';
import Grid2 from '@mui/material/Unstable_Grid2/Grid2';

// import { actionAboutMe, actionDownloadFeed } from '../redux/action';
import { actionAboutMe, actionDownloadFeed } from '../redux/thunks';
import { CardFeed } from './card_feed';
import { CAboutMe } from './aboutMe';
import Recommended from './recommended';


const Item = styled(Paper)(() => ({
    padding: '0 10px',
    marginBottom: 10,
    borderRadius: 0,
    boxShadow: 'none',
}))


function Feed({ feed, loadFeed }) {
    const dispatch = useDispatch()

    const [posts, setPosts] = useState(feed)

    const newPosts = useSelector(state => state.feed?.AddFeed?.payload)

    // useEffect((() => {
    //     if (newPosts) {
    //         setPosts([...posts, ...newPosts])
    //     }
    // }), [newPosts])

    // чекер дна страницы
    window.onscroll = async function feedScroll() {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            const downloadedPosts = await dispatch(actionDownloadFeed(feed.length))

            // добавляем новые посты в общй массив постов
            downloadedPosts.map(post => feed.push(post))
        }
    }


    // console.log('feed: ', feed)
    // console.log('posts: ', posts)


    useEffect(() => { loadFeed() }, [])

    return (
        <Container sx={{
            width: '90%',
            mt: 1
        }}>
            <Box sx={{
                flexGrow: 1
            }}>
                <Grid2 container spacing={2}>
                    <Grid2 xs={7}>
                        <Item>
                            {feed && feed.map(post => <Item key={post._id}><CardFeed postData={post} /></Item>)}
                        </Item>
                    </Grid2>
                    <Grid2 xs={5}>
                        <Item sx={{
                            position: 'fixed'
                        }}>
                            <CAboutMe />

                            <Recommended />
                        </Item>
                    </Grid2>
                </Grid2>
            </Box>
        </Container>
    )
}

export const CFeed = connect(state => ({ feed: state.feed?.MyFeed?.payload }), { loadFeed: actionAboutMe })(Feed)
