import React, { useContext, useEffect } from 'react'
import Search from '../Search';
import Contacts from '../Contacts';
import "./SideBar.css";
import { SocketContext } from '../../contexts/SocketProvider';
import { ChatContext } from '../../contexts/ChatProvider';


function SideBar() {

    const socket = useContext(SocketContext);

    const {
        contacts,
        setContacts,
        // setLastMessages,
        search,
    } = useContext(ChatContext);

    useEffect(() => {

        const fetchData = async () => {

            if (!socket) return;
            socket.on("contacts", (contacts) => {
                // console.log(contacts);
                var newContacts = contacts;

                newContacts.sort((a, b) => b.last_message.send_at - a.last_message.send_at);

                setContacts(newContacts);  // set Contacts
                // setLastMessages(contacts.map((contact) => contact.last_message)); // set Last messages
            });

            socket.emit("get_contacts");
        }

        fetchData();

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

    useEffect(() => {

        if (!socket) return;

        if (search.trim() == "") return;

        socket.on("search_results",(contacts)=>{
            setContacts(contacts);
        })
        socket.emit("search_contacts",search);

        const cleanUp = () => {
            socket.off("search_results");
        }
        return cleanUp;
    }, [socket, search])


    return (

        <div className='side_bar'>
            <Search />
            <Contacts />
        </div>
    )
}

export default SideBar