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 { MessageContainer, MessageFooter, MessageOwner, MessageText, MessageWrapper, TimeMessage } from "./Message.style";
import { saveAs } from "file-saver";
import { MemoMessageMediaContainer, MessageMediaContainer } from "../MessageMediaContainer/MessageMediaContainer";
import { ForwardedMessage } from "../ForwardedMessage/ForwardedMessage";




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

	const owner = true;
  
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);
    const handleClick = (event) => {
      setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
      setAnchorEl(null)
    };


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