import { Avatar, ListItem } from "@mui/material";
import { useEffect } from "react";
import { useContext, useState } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { backendURL } from "../../helpers/gql";
import { ContextID } from "../../pages/MainPage";
import { TimeLastMessage } from "../Time/Time";
import { ChatListItemLink, ChatListItemContent, ChatListItemTitle, ChatListItemWrapper, ChatListLastMessage, ChatListItemHeader, ChatListItemFooter } from "./ChatListItem.style";
import OwnerStar from "./icons8_star.png";
import OnwerStarActive from "./icons8_star_white.png";
const ChatListItem = ({chat, handleSetId, isActive, currUserId}) => {

    return (
            <ChatListItemWrapper isActive={isActive} onClick={() => handleSetId(chat._id)}>
            
                <ChatListItemLink to={`/main/${chat._id}`}>
                    <Avatar
                        alt={chat.title}
                        src={`${backendURL}/${chat.avatar?.url || ''}`}
                        sx={{ width: 45, height: 45, mr: '20px'}}
                    />
                    <ChatListItemContent>
                        <ChatListItemHeader>
                            <ChatListItemTitle isActive={isActive}>{chat.title}
                                {currUserId === chat?.owner?._id && <img src={isActive ? OnwerStarActive : OwnerStar} alt="ownerStar"/>}
                            </ChatListItemTitle>
                            <TimeLastMessage isActive={isActive} timestamp={ + chat.lastMessage?.createdAt}/>
                        </ChatListItemHeader>
                        
                        <ChatListItemFooter>
                            {chat.lastMessage ?
                                <ChatListLastMessage isActive={isActive}>
                                    <span>{(currUserId == chat.lastMessage?.owner._id) ? 'You' : chat.lastMessage?.owner.nick}:</span>
                                    {chat.lastMessage?.text?.replace(/ /g, "\u00a0") || ''}
                                </ChatListLastMessage> 
                            : <div></div>}
                            {/* <div>2</div> */}
                        </ChatListItemFooter>
                        

                    </ChatListItemContent>
                </ChatListItemLink> 
            
            </ChatListItemWrapper>
    )
}

export default connect(state => ({currUserId: state.auth?.payload?.sub?.id}))(ChatListItem);