import React, { useContext, useEffect, useState } from 'react'
import Contact from '../Contact';
import "./Contacts.css";
import { UserContext } from '../../contexts/UserProvider';
import { ChatContext } from '../../contexts/ChatProvider';
import { SocketContext } from '../../contexts/SocketProvider';



function Contacts({ }) {

    // const [activeContact, setActiveContact] = useState({});
    const {
        contacts,
        setContacts,
        currentChat,
        setCurrentChat,
        lastMessages,
    } = useContext(ChatContext);
    const { user } = useContext(UserContext);
    const socket = useContext(SocketContext);
    // handleClick


    useEffect(() => {
        if (!socket) return;
        socket.on("contact", (contact) => {
            var newContacts = [...contacts, contact];
            
            newContacts.sort((a,b)=>b.last_message.send_at - a.last_message.send_at);

            
            setContacts(newContacts);
        });

        const cleanUp = () => {
            if (!socket) return;
            socket.off("contact");
        }
        return cleanUp;
    }, [socket])


    return (
        <div className='contacts'>


            {
                contacts.map((contact) => (
                    // console.log("contact.last_message",contact,contact.last_message),
                    // console.log(user.id),
                    <Contact
                        key={contact.id}
                        onClick={() => { setCurrentChat(contact) }}
                        profile_pic={"logo512.png"}
                        name={contact.id}
                        lastmessage={contact.chat_data.last_message ? contact.chat_data.last_message.content:null}
                        unseen_count={contact.chat_data.unseen_count ? contact.chat_data.unseen_count:null}
                        isActive={currentChat.id == contact.id}
                    />
                ))
            }
        </div>
    )
}

export default Contacts