import React, { useState, useEffect } from 'react';
import { Link, useParams } from 'react-router-dom';
import { history } from '../history/';
import '../App.css';
import store from '../store';
import { actionAboutMe } from '../store/actions/action-aboutMe'
import backgroundChat from '../img/back.JPG'
import { actionChatOne } from '../store/reducers/chat-reducer';



export const ChatPage = ({ onCreateMsg, match: { params: { _id } }, chats, getData, userName }) => {
    const [chatList, setChatList] = useState(chats || [])
    const [messageList, setMessageList] = useState([])
    const [msgAdd, setMsgAdd] = useState("")

    const CreationMsg = () => {
        onCreateMsg(msgAdd)
        setMsgAdd('')
    }


    useEffect(() => {

        async function getDataFunc() {
            const res = await getData(_id)

            setChatList(res.chats)
            setMessageList(res.chats?.message)
        }

        getDataFunc()
    }, [_id])

    function handleClick(_id) {
        const filteredChatList = chatList.filter((item) => item._id === _id)
        console.log(filteredChatList)
        setMessageList(filteredChatList[0].messages)
        
    }



    return (
        <>
            <div className='chatPage'>
                <aside>
                    <div className="row">
                        <div className="col-12">
                            <div id="list-example" className="list-group">
                                <a href="/create-chat" className='linkToCreate'><h1>Создать чат</h1></a>
                                <ul className='chatAside'>{chatList.map((item, index) =>
                                    <a className="list-group-item list-group-item-action">
                                        <Link to={`/chat/${item._id}`}>
                                            <li onClick={() => handleClick(item._id)} className='chatLi' key={index}>
                                                <h3>Chat: {item.title}</h3>
                                                {/* {item.lastMessage ? <h6>Last Message: {item.lastMessage.text}</h6> : []} */}
                                            </li>
                                        </Link>
                                    </a>
                                )}
                                </ul>


                            </div>
                        </div>
                    </div>
                </aside>
                <main className='chatMain'>
                    <div className='chatPrewiew'>
                        <h4>select a chat to start messaging</h4>
                    </div>
                </main>
            </div>
        </>
    )
}