import { makeStyles } from "@material-ui/core/styles";
import SendIcon from '@mui/icons-material/Send';
import MicNoneIcon from '@mui/icons-material/MicNone';
import AttachFileIcon from '@mui/icons-material/AttachFile';
import SentimentSatisfiedAltIcon from '@mui/icons-material/SentimentSatisfiedAlt';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import Avatar from '@mui/material/Avatar';
import CloseIcon from '@mui/icons-material/Close';
import { useState } from "react";
import { useSelector } from "react-redux";

import FilesMenu from "../FilesMenu";
import NotDone from "../../../../reusableComponents/NotDone";
import {
    sentMessageById, sentImgMessageById, sentAudioMessageById,
    sentVideoMessageById,sentFileMessageById
} from '../../../../../api-data'
import { getChat } from '../../../../../redux/chat/selector'
import { playNotification } from "../../../../../helpers";
import { typingChat } from "../../../../../api-data";


const useStyles = makeStyles({   
    container: {
        display: "flex",
        justifyContent: "space-between",
        alignContent: 'flex-end',
        alignItems:'flex-end',
        width: 700,
        position: 'fixed',
        bottom: 20,
        paddingTop:10,
    },
    inputContainer: {
        position:'relative',
        minWidth: 634,
        maxWidth: 634,
        maxHeight:56,
        display: 'flex',
        flexWrap: 'nowrap',
        alignContent: 'center',
        alignItems: 'center',
        color: '#6b6b6b',
        backgroundColor: '#ffffff',
        borderRadius: 8,
        padding: 10,
        marginRight: 10,
      "&:after": {
        content: "''",
        position: "absolute",
        width: "0",
        height: "0",
        borderBottom: "15px solid #ffffff",
        borderLeft: "15px solid transparent",
        borderRight: "15px solid transparent",
        bottom: "0",
        right: "-15px"
      },
      "&:before": {
        content: "''",
        position: "absolute",
        width: "0",
        height: "0",
        borderBottom: "17px solid #ffffff",
        borderLeft: "16px solid transparent",
        borderRight: "16px solid transparent",
        bottom: "-1px",
        right: "-17px"
      }        
    },
    textarea: {
        minWidth: 550,
        maxWidth: 550,
        outline: 'none',
        border:'none',
        padding: '0px 10px',
        marginLeft: 8,
        marginRight: 8,
        overflowY:'auto',
        resize: 'none',
        height: 'auto',
    },
    attachIcon: {
        transform:'rotate(30deg)',  
    },
    filesMenu: {
      background: '#fdfdfd',
      position: 'absolute',
      width: 300,
      maxWidth: '100%',
      left: 406,
      bottom:64,
      zIndex: 10,
      visibility: 'visible',
      borderRadius: 10,
      padding: '4px 6px',
    },
    emoji: {
      background: '#fdfdfd',
      position: 'absolute',
      width: 350,
      height:350,
      left: 0,
      bottom:64,
      zIndex: 10,
      visibility: 'visible',
      borderRadius: 10,
      padding: '0px 6px',
    },     
    avatar: {
        '&:hover': {
            backgroundColor: 'rgb(41, 139, 231)',
            color: '#ffffff',
        }
    },
    avatarArrow: {
        left: 120,
        bottom:200,
        '&:hover': {
            backgroundColor: 'rgb(41, 139, 231)',
            color: '#ffffff',
        }
    },
    iconCancel: {
        position: 'absolute',
        left:-45,
        display:'flex',
        backgroundColor: '#945353',
        width: 56,
        height: 56,
        color: '#6b6b6b',
        borderRadius: '50%',
        '&:hover': {
            backgroundColor: 'rgb(218, 18, 18)',
            color: '#ffffff',
        }
    },
});

interface ISendMessage{
    isArrow:boolean,
    handleScrollTo:() => void
}

const SendMessage = ({isArrow,handleScrollTo}:ISendMessage) => {
    const classes = useStyles();
    const { companionId } = useSelector(getChat)
    const [value, setValue] = useState<string>('')
    const [file, setFile] = useState<any>(null)
    const [isOpenMenu, setIsOpenMenu] = useState<boolean>(false)
    const [isOpenEmoji, setIsOpenEmoji] = useState<boolean>(false)
    const [type, setType] = useState<string>('')
    const sentMessage = async () => {
        setValue('')
        setFile(null)
        isOpenMenu&&setIsOpenMenu(false)
        isOpenEmoji && setIsOpenEmoji(false)
        if (value) sentMessageById(companionId, value)
        if (file && file.type&&type) {
            if (file.type.includes('image') && type === 'content') {
              const formData: any = new FormData()
              formData.append("image", file);
              await sentImgMessageById(companionId, formData)
            }
            if (file.type.includes('audio') && type === 'content') {
              const formData: any = new FormData()
              formData.append("audio", file);
              sentAudioMessageById(companionId, formData)
            }
            if (file.type.includes('video') && type === 'content') {
              const formData: any = new FormData()
              formData.append("video", file);
              sentVideoMessageById(companionId, formData)                
            }
            if (file.type.includes('application') && type === 'application') {
              const formData: any = new FormData()
              formData.append("file", file);
              sentFileMessageById(companionId, formData)   
            }            
        }
        setTimeout(handleScrollTo, 3000);
        playNotification('http://localhost:3000/send.mp3')
    }    
    const handleTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        isOpenMenu&&setIsOpenMenu(false)
        isOpenEmoji && setIsOpenEmoji(false)
        setValue(e.target.value)
    }
    const handleFocusTextarea = () => {
        typingChat(companionId,true)
        isOpenMenu&&setIsOpenMenu(false)
        isOpenEmoji&&setIsOpenEmoji(false) 
    }
    const handleBlurTextarea = () =>  typingChat(companionId,false) 
      
    const handleLeaveInput = (e: any) => {
        if (e.clientX > 1450 || e.clientX < 850) {
        isOpenMenu&&setIsOpenMenu(false)
        isOpenEmoji&&setIsOpenEmoji(false)  
        }
    }
    const handleMoveInput = (e: any) => {
        if (e.clientX < 1250 && e.clientX > 1200) {
        isOpenMenu&&setIsOpenMenu(false)
        isOpenEmoji&&setIsOpenEmoji(false)   
        }
    }
    const handleKeyPres = (e: any) => {
        if(e.code === 'Enter'&& value) sentMessage()
    }
    const handleEnterFileMenu = () => !isOpenMenu&&setIsOpenMenu(true)
    const handleLeaveFileMenu = () => isOpenMenu&&setIsOpenMenu(false)
    const handleEnterEmoji = () => !isOpenEmoji&&setIsOpenEmoji(true)
    const handleLeaveEmoji = () => isOpenEmoji && setIsOpenEmoji(false)
    const handleClearMessage = () => setFile(null)

    return (
        <div className={classes.container} style={{borderTop:isArrow?'solid 1px #ffffff':'none'}} >            
            <div onMouseLeave={handleLeaveInput} onMouseMove={handleMoveInput}
                onKeyPress={handleKeyPres} className={classes.inputContainer}>
                <CloseIcon onClick={handleClearMessage} fontSize="small" className={classes.iconCancel}
                    sx={{backgroundColor:'#ffffff',width:36,height:36,color:'#949393',display:file?'inline-block':'none'}}/>
                <SentimentSatisfiedAltIcon onMouseEnter={handleEnterEmoji}
                    fontSize='medium' sx={{ color: isOpenEmoji ? 'rgb(41, 139, 231)' : '#6b6b6b' }}/>
                <div onMouseLeave={handleLeaveEmoji} style={{display:isOpenEmoji?'block':'none'}} className={classes.emoji}>
                    <NotDone name='Emoji Bar'/>
                </div>                
                <textarea disabled={file?true:false} value={value} onBlur={handleBlurTextarea} onFocus={handleFocusTextarea} onChange={handleTextarea}
                    className={classes.textarea} placeholder={file?'Press onto Plane to send or Cross to remove':'Message'} rows={1}></textarea>
                <AttachFileIcon onMouseEnter={handleEnterFileMenu} className={classes.attachIcon}
                    fontSize='medium'  sx={{color: isOpenMenu?'rgb(41, 139, 231)':'#6b6b6b'}}/>
                <div onMouseLeave={handleLeaveFileMenu} style={{display:isOpenMenu?'block':'none'}} className={classes.filesMenu}>
                    <FilesMenu setFile={setFile} setValue={setValue} setIsOpenMenu={setIsOpenMenu} setType={setType}/>
                </div>
                <Avatar onClick={handleScrollTo} className={classes.avatarArrow} sx={{
                  backgroundColor: '#ffffff',
                   width: 56, height: 56 ,color: '#6b6b6b',display:isArrow?'flex':'none'}}>
                  <ArrowDownwardIcon fontSize="medium" />
                </Avatar>                 
            </div>  
            {value || file ?
             <Avatar onClick={sentMessage} className={classes.avatar} sx={{
               backgroundColor: '#ffffff',
               width: 56, height: 56 ,color: 'rgb(41, 139, 231)'}}>
                  <SendIcon fontSize="medium" />
            </Avatar> :
             <Avatar className={classes.avatar} sx={{
               backgroundColor: '#ffffff',
                    width: 56, height: 56, color: '#6b6b6b'}}>                   
                    <MicNoneIcon fontSize="medium" />                    
            </Avatar>}
        </div>            
    )
}

export default SendMessage