import { useEffect, useRef, useState } from "react"
import { connect } from "react-redux"
import { actionSendMessage, actionUpsertMSG } from "../../actions/actionsMessages"
import { InputAreaWrapper, TextArea} from "./InputArea.style";
import Plane from "./icons8-plane.png";
import MessageDropZone from "../DropZone/MessageDropZone/MessageDropZone";
import { actionAddDraftMessage, actionDeleteDraftMessageId, actionDeleteReplyMessageId, actionSetInputMessageValue } from "../../reducers/chatReducer";

import SendRoundedIcon from '@mui/icons-material/SendRounded';
import ReplyMessage from "../MessageDraft/ReplyMessageDraft";
import { MessageDraftBox } from "../MessageDraft/MessageDraftBox";
import InputAreaMessageEditor from "./InputAreaMessageEditor";


const InputArea = ({sendMessage, deleteDraftMessage, chatId, chats, setInputValue, modal: {content, isOpen}}) => {
    const message = chats[chatId]?.draft?.mainInputValue?.message;
    const inputValue = chats[chatId]?.draft?.mainInputValue?.value || '';
    let replyMessageId = (message && typeof message !== 'object') ? message : null;
    let forwardedMessageId = (message && typeof message === 'object') ? message._id : null;
    console.log(forwardedMessageId)

	return (chats[chatId]?.draft?.messageEditor && !chats[chatId]?.draft?.messageEditor?.message?.media) ? 
        <InputAreaMessageEditor chatId={chatId}/> 
        :
		<InputAreaWrapper>
            <MessageDraftBox chat={chats[chatId]}>
                
            </MessageDraftBox>
            
            <div style={{display: 'flex', alignItems: 'center', padding: '10px 0'}}>
                <MessageDropZone chatId={chatId}/>
                <TextArea
                    value={content === 'messageMediaModal' && isOpen ? '' : inputValue}         
                    onChange={e=>{setInputValue(chatId, e.target.value, 'mainInputValue')}}
                    maxRows={8}
                    placeholder="Write a message..." 
                />
                {inputValue ? 
                <SendRoundedIcon
                    style={{margin: '0 16px', cursor: "pointer"}}
                    color="primary"
                    // src={Plane} 
                    onClick={
                        async() => {
                            let val = await sendMessage(null, chatId, inputValue.replace(/^\s+|\s+$/g, ''), null, replyMessageId, forwardedMessageId);
                            (val?.replyTo?._id || val?.forwarded?._id) && deleteDraftMessage(chatId, null)
                            val && setInputValue(chatId, "", 'mainInputValue')
                        }
                    }
                /> : <div></div>}
            </div>
        </InputAreaWrapper>
	
}

export default connect(state => ({chats: state.chats, modal: state?.modal}), {
    sendMessage: actionSendMessage,
    setInputValue: actionSetInputMessageValue,
    deleteDraftMessage: actionAddDraftMessage
})(InputArea);