import { makeStyles } from "@material-ui/core/styles";
import SendIcon from '@mui/icons-material/Send';
import MicNoneIcon from '@mui/icons-material/MicNone';
import VideocamIcon from '@mui/icons-material/Videocam';
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 { useReactMediaRecorder } from "react-media-recorder";
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 { getIsOpen } from '../../../../../redux/control/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: 15,       
    },
    textarea: {
        minWidth: 550,
        maxWidth: 550,
        outline: 'none',
        border:'none',
        padding: '0px 10px',
        marginLeft: 8,
        marginRight: 8,
        overflowY:'auto',
        resize: 'none',
        height: 'auto',
        '&::placeholder': {
            color: 'rgb(82, 82, 82)',
            fontWeight: 600
        }
    },    
    attachIcon: {
        transform:'rotate(30deg)',  
    },
    filesMenu: {
      background: '#fdfdfd',
      position: 'absolute',
      width: 300,
      maxWidth: '100%',
      left: '61%',
      bottom:90,
      zIndex: 10,
      visibility: 'visible',
      borderRadius: 10,
      padding: '4px 6px',
    },
    emoji: {
      background: '#fdfdfd',
      position: 'absolute',
      width: 350,
      height:350,
      bottom:90,
      zIndex: 10,
      visibility: 'visible',
      borderRadius: 10,
      padding: '0px 6px',
    },
    iconCancel: {
        position: 'absolute',
        left: -72,
        bottom:-1,
        display:'flex',
        backgroundColor: '#ffffff',
        color: 'rgb(243, 69, 69)',
        border:'solid 4px rgb(243, 69, 69)',
        borderRadius: '50%',
        '&:hover': {
            backgroundColor: 'rgb(243, 69, 69)',
            color: '#ffffff',
        }
    },    
    avatar: {
        '&:hover': {
            backgroundColor: 'rgb(41, 139, 231)',
            color: '#ffffff',
        }
    },
    avatarCamera: {
        position: 'absolute',
        left: -72,
        bottom:-1,
        display: 'flex',
        borderRadius: '50%',
        zIndex: 10,
        border: 'solid 14px #ffffff',
        '&:hover': {
            backgroundColor: 'rgb(41, 139, 231)',
            border:'solid 14px rgb(41, 139, 231)',
            color: '#ffffff',
        }
    },  
    avatarArrowWrapper: {
        position:'absolute',
        right: -140,
        bottom: 200,
        width: 56,
    },    
    avatarArrow: {
        cursor:'pointer',
        '&:hover': {
            backgroundColor: 'rgb(41, 139, 231)',
            color: '#ffffff',
        }
    },
    listSeenIcon: {
        position: 'absolute',
        top: -8,
        left: 16,
        borderRadius: '50%',
        color: '#ffffff',
        border: 'none',
        height: 24,
        width: 24,
        textAlign: 'center',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        alignContent: 'center',
        fontSize: 12,
        zIndex: 10,
        cursor:'pointer',
    },   
    overlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      width: '100vw',
      height: '100vh',
      zIndex:100
    },  
});

interface ISendMessage{
    isArrow: boolean,
    isNew: {new:number,mute:boolean},
    handleScrollTo:() => void
}

const SendMessage = ({isArrow,isNew,handleScrollTo}:ISendMessage) => {
    const classes = useStyles();
    const { companionId } = useSelector(getChat)
    const isOpen = useSelector(getIsOpen)
    const [value, setValue] = useState<string>('')
    const [file, setFile] = useState<any>(false)
    const [isOpenMenu, setIsOpenMenu] = useState<boolean>(false)
    const [isOpenEmoji, setIsOpenEmoji] = useState<boolean>(false)
    const [isRecording, setIsRecording] = useState<boolean>(false)
    const [isFilming, setIsFilming] = useState<boolean>(false)    
    const [type, setType] = useState<string>('')
    const { status, startRecording, stopRecording, mediaBlobUrl, clearBlobUrl } = useReactMediaRecorder({ audio: true });
    const { status: _status, startRecording: _startRecording, stopRecording: _stopRecording,
        mediaBlobUrl: _mediaBlobUrl,clearBlobUrl:_clearBlobUrl } = useReactMediaRecorder({ video: true });
    const clearMessage = () => {
        file &&setFile(false)
        isRecording && setIsRecording(false)
        isFilming && setIsFilming(false)
        value && setValue('')
        type && setType('')
        mediaBlobUrl && clearBlobUrl()
        _mediaBlobUrl && _clearBlobUrl()
        isOpenMenu && setIsOpenMenu(false)
        isOpenEmoji && setIsOpenEmoji(false)
    
    }
    const sentMessage = async () => {
        if (value) sentMessageById(companionId, value)
        if (mediaBlobUrl && type === 'recording') {
            const audio = new XMLHttpRequest();
            audio.open('GET', mediaBlobUrl, true);
            audio.responseType = 'blob';
            audio.onload = () => {
            if (audio.status === 200) {
                const name = `audioMessage${new Date().getTime()}.mp3`
                const blob = audio.response
                const file = new File([blob], name, {
                  type: 'audio/mpeg'
                })
                const formData: any = new FormData()
                formData.append("audio", file)
                sentAudioMessageById(companionId, formData)
                clearBlobUrl()
               }
            }
            audio.send();
        }
        if (_mediaBlobUrl && type === 'filming') {
            const video = new XMLHttpRequest();
            video.open('GET', _mediaBlobUrl, true);
            video.responseType = 'blob';
            video.onload = () => {
            if (video.status === 200) {
                const name = `videoMessage${new Date().getTime()}.mp4`
                const blob = video.response
                const file = new File([blob], name, {
                    type: 'video/mp4'
                })
                const formData: any = new FormData()
                formData.append("video", file)
                sentVideoMessageById(companionId, formData)
                _clearBlobUrl()
                }
            }
            video.send();
        }        
        if (file && 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)   
            }
        }
        clearMessage()
        playNotification('http://localhost:3000/send.mp3')
        setTimeout(handleScrollTo, 4000);
    }    
    const handleTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => setValue(e.target.value)
    const handleFocusTextarea = async () => await typingChat(companionId,true)
    const handleBlurTextarea = async () => await typingChat(companionId,false) 
    const handleOpenFileMenu = () => !isOpenMenu&&setIsOpenMenu(true)
    const handleCloseFileMenu = (e:any) => e.target.id === 'overlay'&&isOpenMenu&&setIsOpenMenu(false) 
    const handleOpenEmoji = () => !isOpenEmoji&&setIsOpenEmoji(true)
    const handleCloseEmoji = (e: any) => e.target.id === 'overlay'&&isOpenEmoji&&setIsOpenEmoji(false) 
    const handleRecording = () => {
        if (isRecording) return stopRecording()
        startRecording()
        setType('recording')
        setIsRecording(true) 
    }
    const handleFilming = () => {
        if (isFilming) return _stopRecording()
        _startRecording()
        setType('filming')
        setIsFilming(true)
        
    }

    return (
        <div className={classes.container} style={{borderTop:isArrow?'solid 1px #ffffff':'none'}} >            
            <div className={classes.inputContainer}>
                <CloseIcon onClick={clearMessage} fontSize="small" className={classes.iconCancel}
                    sx={{width: 56, height: 56, display: file || value || status === 'stopped'
                    || _status === 'stopped' ? 'inline-block' : 'none'}} />
                <VideocamIcon onClick={handleFilming} className={classes.avatarCamera}
                    sx={{backgroundColor: '#ffffff', color: '#7c7c7c', width: 56, height: 56}}
                    style={{display: status !== 'idle' || _status === 'stopped' || file || value ? 'none' : 'block',
                    animation:isFilming ? 'ripple 1.2s infinite ease-in-out': 'none'}} />
                <SentimentSatisfiedAltIcon onClick={handleOpenEmoji}
                    fontSize='medium' sx={{color: isOpenEmoji ? 'rgb(41, 139, 231)' : '#6b6b6b', cursor: 'pointer',
                    '&:hover': { color: 'rgb(41, 139, 231)'}}}/>
                <div onClick={handleCloseEmoji} className={classes.overlay} id='overlay'
                  style={{ display: isOpenEmoji ? 'block':'none'}}>
                   <div className={classes.emoji} style={{left: isOpen&&isOpen !== 'menu'?'31%':'44%'}}>
                      <NotDone name='Emoji Bar'/>
                   </div>  
                </div>
                <textarea disabled={file ? true : false} value={value} onBlur={handleBlurTextarea}
                    onFocus={handleFocusTextarea} onChange={handleTextarea} className={classes.textarea}
                    placeholder={file ? 'The File is ready to send' : status === 'idle' && _status === 'idle' ? 'Message ' :
                    `${status === 'stopped' || _status === 'stopped' ?'Recorded':'Recording in progress'}`} rows={1}>
               </textarea>
                <AttachFileIcon onClick={handleOpenFileMenu} className={classes.attachIcon}
                    fontSize='medium' sx={{
                        color: isOpenMenu ? 'rgb(41, 139, 231)' : '#6b6b6b', cursor: 'pointer',
                        '&:hover': { color: 'rgb(41, 139, 231)' }
                    }} />
                <div onClick={handleCloseFileMenu} className={classes.overlay} id='overlay'
                    style={{ display: isOpenMenu ? 'block':'none'}}>
                    <div className={classes.filesMenu} style={{left: isOpen&&isOpen !== 'menu'?'48%':'61%'}}>
                      <FilesMenu setFile={setFile} setValue={setValue} setIsOpenMenu={setIsOpenMenu} setType={setType}/>
                    </div>
                </div>
                <div className={classes.avatarArrowWrapper} style={{display: isArrow ? 'block' : 'none'}}>
                    <button onClick={handleScrollTo} style={{display: isNew.new ? 'block' : 'none',
                     background: isNew.mute ? '#a7aaa7' : '#0ac40a'}}
                     className={classes.listSeenIcon}>{isNew.new}</button>
                   <Avatar onClick={handleScrollTo} className={classes.avatarArrow}
                       sx={{backgroundColor: '#ffffff', width: 56, height: 56,color: '#6b6b6b'}}>
                     <ArrowDownwardIcon fontSize="medium" />  
                   </Avatar>                    
                </div>
            </div>  
            {value || file || status === 'stopped'  || _status === 'stopped' ?
             <Avatar onClick={sentMessage} className={classes.avatar} sx={{
                backgroundColor: '#ffffff',color: 'rgb(41, 139, 231)', width: 56, height: 56}}>
             <SendIcon fontSize="medium" />
                </Avatar> : null}
            {!value && !file && status !== 'stopped' && _status === 'idle' ? <Avatar onClick={handleRecording}
                className={classes.avatar} style={{animation:isRecording ? 'ripple 1.2s infinite ease-in-out': 'none'}}
                sx={{backgroundColor: isRecording ? 'rgb(41, 139, 231)' : '#ffffff',
                color: isRecording ? '#ffffff' : '#6b6b6b', width: 56, height: 56}}>
                <MicNoneIcon fontSize="medium" />
            </Avatar>:null}            
        </div>            
    )
}

export default SendMessage