import { connect } from "react-redux"
import { Message } from "../Message/Message"
import { MessagesAreaWrapper, SimpleBarWrapper } from "./MessagesArea.style"
import 'simplebar/dist/simplebar.min.css';
import InfiniteScroll from 'react-infinite-scroll-component';
import { useEffect, useRef, useState } from "react";
import { actionGetMessageForChat } from "../../actions/actionGetMessageForChat";
// import { ClassNames } from "@emotion/react";

// const Test = ({messagesByChat}) => {
// 	useEffect(() => {
// 		console.log('i am from body')
// 		return () => {
// 			console.log('i was unMount')
// 		}
// 	}, [])

// 	return (
// 		<div style={{display: 'flex', flexDirection: 'column-reverse'}}>
			
// 		</div>
// 	)
// }

const MessagesArea = ({chats, chatId, getMessages}) => {
	
	// console.log(chats[chatId].messages)
	const messagesByChat = Object.values(chats[chatId]?.messages || []);
	const ref = useRef();
	let timer
	function infinityScroll () {
		// console.log('количество скроллов')
		clearTimeout(timer);
		timer = setTimeout(async() => {
			// console.log('количество таймеров')
			const offset = 600;
			const scrollElem = ref.current?.contentWrapperEl;
			if(scrollElem.scrollHeight - (scrollElem.clientHeight - scrollElem.scrollTop)  < offset){
				let data = await getMessages(chatId);
				if (data.length < 20) ref.current?.contentWrapperEl.removeEventListener("scroll", infinityScroll);
				// console.log('вызов')
			}
		},30)
	}
	
	useEffect(() => {
		ref.current?.contentWrapperEl.addEventListener("scroll", infinityScroll);
		// Remove listener (like componentWillUnmount)
		// console.log('i am working from useEffect');
		return () => {
			ref.current.contentWrapperEl.scrollTop = 0;
			ref.current?.contentWrapperEl.removeEventListener("scroll", infinityScroll);
			console.log("unMount from parent")
		};
	  }, [chatId]);
	
	
	
	return (
		
			<MessagesAreaWrapper >
					 <SimpleBarWrapper  ref={ref}> 
						{messagesByChat.map((item) => <Message key={item._id} chatId={chatId} mes={item}/>)}
					 </SimpleBarWrapper> 
			</MessagesAreaWrapper>
	)
}

export default connect(state=>({chats: state.chats || {}}), {getMessages : actionGetMessageForChat})(MessagesArea)