import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { backendURL } from "../../helpers/gql";
import MessageOptions from "../MessageOptions/MessageOptions";
import { ReplyMessage } from "../ReplyMessage/ReplyMessage";
import { convert } from "../Time/Time";
import { ForwardedMessageHeader, MessageContainer, MessageFooter, MessageOwner, MessageText, MessageWrapper, TimeMessage } from "./Message.style";
import { saveAs } from "file-saver";
import { MemoMessageMediaContainer, MessageMediaContainer } from "../MessageMediaContainer/MessageMediaContainer";




export const Message = ({mes, chatId}) => {

	const owner = true;
	const checkedMessage = mes.forwarded ? mes.forwarded : mes; //check message (it has forwarded message or not, if it has return forwarded mes)
  
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);
    const handleClick = (event) => {
      setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
      setAnchorEl(null)
    };

	
	return (
        <div>
			<MessageWrapper >
					<MessageContainer onClick={(e) => {handleClick(e)}}>
						{mes.forwarded && <ForwardedMessageHeader>{`Forwarded from ${checkedMessage?.owner?.nick || ''}`}</ForwardedMessageHeader>}
						{checkedMessage?.replyTo && <ReplyMessage owner={owner} message={checkedMessage.replyTo}/>}
						{checkedMessage?.media && checkedMessage?.media?.length !==0 && <MemoMessageMediaContainer media={checkedMessage.media}/>}
						<MessageText>{checkedMessage?.text?.replace(/ /g, "\u00a0") || ''}</MessageText>
						<MessageFooter>
							<MessageOwner>{checkedMessage.owner.nick || 'nick'}</MessageOwner>
							<TimeMessage owner={owner}>{convert(checkedMessage.createdAt).getTime()}</TimeMessage>
						</MessageFooter>
					</MessageContainer>
			</MessageWrapper>
            <MessageOptions message={checkedMessage} chatId={chatId} handleClose={handleClose} open={open} anchorEl={anchorEl}/>
         </div>)
			
			
	
}