import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { backURL } from "../constants";
import { Link } from "react-router-dom";
import { AvatarStub, color } from "../components/AvatarStub";
import { actionFullMsgsByChat } from "../actions";
import { actionUserFindOne, store } from "../reducers";
import { OneChat } from "./MsgPage";
import Button from "react-bootstrap/esm/Button";
import { CSendingField } from "../components/SendMsg";

// const ChatsPage = ({ chats = [], }) => {
//     return (
//         <>
//             <div className="chatsContainer">
//                 {chats.map((chat, _id) => (
//                     <>

//                         <Link className="chatsList"  to={`/main/${chat._id}`}>
//                             {chat.avatar?.url ? (
//                                 <img
//                                     className="smallForChat"
//                                     src={backURL + chat.avatar?.url}
//                                 />
//                             ) : (
//                                 <AvatarStub
//                                     login={
//                                         chat.title !== null
//                                             ? chat.title
//                                             : "chat without title"
//                                     }
//                                     color={color()}
//                                 />
//                             )}
//                             <h5 className="chatTitle">
//                                 {chat.title !== null
//                                     ? chat.title
//                                     : "chat without title"}
//                             </h5>

//                         </Link>
//                     </>
//                 ))}
//                 <Link className="newChatButton" to="/newchat">
//                     +
//                 </Link>
//             </div>
//             <div>
//                 {chats.map((chat) =>  <CChatList chatId={chat._id} chat={chat.messages} key={chat._id}/>)}

//             </div>
//         </>
//     );
// };

// export const CChatsPage = connect(
//     (state) => ({
//         chats: Object.values(state.chats).filter((el) => el._id),
//         // chat_Id: state.promise
//     }),
// )(ChatsPage);

export const ChatPage = ({
    match: {
        params: { _id = store.getState().auth?.payload?.sub.id },
    },
    chats,
    getData,
    userName,
}) => {
    const [chatList, setChatList] = useState(chats || []);
    const [messageList, setMessageList] = useState([]);

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

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

        getDataFunc();
    }, [_id]);

    const StrValid = "30";

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

    return (
        <>
            <div className="mainContainer">
                <aside className="chatsContainer">
                    <ul className="chatAside">
                        {chatList.map((item, index) => (
                            <Link
                                className="chatsList"
                                to={`/main/${item._id}`}
                                key={item._id}
                            >
                                {item.avatar?.url ? (
                                    <img
                                        className="smallForChat"
                                        src={backURL + item.avatar?.url}
                                    />
                                ) : (
                                    <AvatarStub
                                        login={
                                            item.title !== null
                                                ? item.title
                                                : "chat without title"
                                        }
                                        color={color()}
                                    />
                                )}
                                <li
                                    onClick={() => handleClick(item._id)}
                                    className="chatLi"
                                    key={item._id}
                                >
                                    <h4>{item.title}</h4>
                                    <h6>
                                        {item.lastMessage?.text.length >
                                        parseInt(StrValid)
                                            ? item.lastMessage?.text.substr(
                                                  0,
                                                  30
                                              ) + "..."
                                            : item.lastMessage?.text.substr(
                                                  0,
                                                  30
                                              )}
                                    </h6>
                                </li>
                            </Link>
                        ))}
                    </ul>
                    <Link className="newChatButton" to="/newchat">
                        +
                    </Link>
                </aside>
                <div className="flexContainer">
                    <main className="chatMain" id="chatMain">
                        {messageList && messageList.length > 0 && (
                            <div className="chatMain">
                                {messageList.map((item1, index) => (
                                    <div
                                        className={
                                            item1.owner.nick ===
                                            store.getState().promise.myProfile
                                                .payload.nick
                                                ? "msgsContainer"
                                                : "msgOtherContainer"
                                        }
                                    >
                                        <div
                                            className={
                                                item1.owner.nick ===
                                                store.getState().promise
                                                    .myProfile.payload.nick
                                                    ? "msgLi"
                                                    : "msgOther"
                                            }
                                            key={index}
                                        >
                                            <h6>{item1.owner.nick}</h6>
                                            <p>
                                                {item1.text
                                                    ? item1.text
                                                    : "No messages"}
                                            </p>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </main>
                    {messageList === undefined ? (
                        <></>
                    ) : (
                        <div className="sendMsgBlock">
                            <div className="sendBlock">
                                <img
                                    src="https://img.icons8.com/ios-filled/344/folder-invoices--v2.png"
                                    className="sandFile"
                                />
                                <textarea
                                    placeholder="Write a message..."
                                    rows="2"
                                />
                            </div>

                            <Button>Send a message</Button>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
};

export const CChatsPage = connect(
    (state) => ({
        chats: state.promise.myProfile?.chats,
        // _id: state.auth?.payload?.sub.id,
    }),
    { getData: actionUserFindOne }
)(ChatPage);
