import React, { useState, useEffect } from 'react';
import Axios from 'axios';
import { useDispatch, useSelector } from 'react-redux';
import { List, Icon, Avatar } from 'antd';
import avatar from './images/avatar.png';
import { saveMessage } from '../functions/actions/digitalHuman_actions';
import Message from './sections/messageChat';
import Card from "./sections/cardChat";
import './styles/digitalHuman.css';
import { FaMicrophone } from "react-icons/fa";
import { IoSend } from "react-icons/io5";

const SpeechRecognition =
    window.SpeechRecognition || window.webkitSpeechRecognition
const mic = new SpeechRecognition();

mic.continuous = true
mic.interimResults = true
mic.lang = 'en-US'

function DigitalHuman() {
    const dispatch = useDispatch();
    const messagesFromRedux = useSelector(state => state.message.messages);
    const [isListening, setIsListening] = useState(false)
    const [note, setNote] = useState(null)


    const [cls, setCls] = useState("green");

    useEffect(() => {
        eventQuery('welcomeToMyWebsite');
    }, [])

    useEffect(() => {
        handleListen()
    }, [isListening])

    const handleListen = () => {
        if (isListening) {
            mic.start()
            mic.onend = () => {
                console.log('continue..')
                mic.start()
            }
        } else {
            mic.stop()
            mic.onend = () => {
                console.log('Stopped Mic on Click')
            }
        }
        mic.onstart = () => {
            console.log('Mics on')
        }

        mic.onresult = event => {
            const transcript = Array.from(event.results)
                .map(result => result[0])
                .map(result => result.transcript)
                .join('')
            console.log(transcript)
            setNote(transcript)
            mic.onerror = event => {
                console.log(event.error)
            }
        }
    }

    const textQuery = async (text) => {
        //  First  Need to  take care of the message I sent     
        let conversation = {
            who: 'user',
            content: {
                text: {
                    text: text
                }
            }
        }

        dispatch(saveMessage(conversation))
        // console.log('text I sent', conversation)
        // We need to take care of the message Chatbot sent 
        const textQueryVariables = {
            text
        }
        try {
            //I will send request to the textQuery ROUTE 
            const response = await Axios.post('/api/dialogflow/textQuery', textQueryVariables)
            for (let content of response.data.fulfillmentMessages) {
                conversation = {
                    who: 'Bot',
                    content: content
                }
                dispatch(saveMessage(conversation))
            }
        } catch (error) {
            conversation = {
                who: 'Bot',
                content: {
                    text: {
                        text: " Error just occured, please check the problem"
                    }
                }
            }
            dispatch(saveMessage(conversation))
        }
    }

    const eventQuery = async (event) => {
        // We need to take care of the message Chatbot sent 
        const eventQueryVariables = {
            event
        }
        try {
            //I will send request to the textQuery ROUTE 
            const response = await Axios.post('/api/dialogflow/eventQuery', eventQueryVariables)
            for (let content of response.data.fulfillmentMessages) {
                let conversation = {
                    who: 'Bot',
                    content: content
                }
                dispatch(saveMessage(conversation))
            }
        } catch (error) {
            let conversation = {
                who: 'Bot',
                content: {
                    text: {
                        text: " Error just occured, please check the problem"
                    }
                }
            }
            dispatch(saveMessage(conversation))
        }
    }
    const keyPressHanlder = (e) => {
        if (e.key === "Enter") {
            if (!e.target.value) {
                return alert('you need to type somthing first')
            }
            //we will send request to text query route 
            textQuery(e.target.value)
            e.target.value = "";
        }
    }

    const onClicksHanlder = () => {
        if (!note) {
            return alert('you need to type somthing first')
        }
        //we will send request to text query route 
        textQuery(note);
        setNote('');
    }

    const renderCards = (cards) => {
        return cards.map((card, i) => <Card key={i} cardInfo={card.structValue} />)
    }
    const renderOneMessage = (message, i) => {
        console.log('message', message)
        // we need to give some condition here to separate message kinds 
        // template for normal text 
        if (message.content && message.content.text && message.content.text.text) {
            return <Message key={i} who={message.who} text={message.content.text.text} />
        } else if (message.content && message.content.payload.fields.card) {
            const AvatarSrc = message.who === 'Bot' ? <img src={avatar} /> : <Icon type="smile" />
            return <div>
                <List.Item style={{ padding: '1rem' }}>
                    <List.Item.Meta
                        description={renderCards(message.content.payload.fields.card.listValue.values)}
                    />
                </List.Item>
            </div>
        }
        // template for card message 
    }

    const renderMessage = (returnedMessages) => {
        if (returnedMessages) {
            return returnedMessages.map((message, i) => {
                return renderOneMessage(message, i);
            })
        } else {
            return null;
        }
    }

    return (
        <div className='digitalHuamn'>
            <div className='avatar'>
                <video height='520px' autoPlay>
                    <source src='/video/result_voice.mp4' type="video/mp4" />
                </video>
            </div>
            <div className='avatar'>
                <div className='chat' style={{
                    height: `465px`,
                    overflow: "scroll",

                }}>
                    <div className='chat_body'>
                        {renderMessage(messagesFromRedux)}
                    </div>
                    <div className='chat_footer'>
                        <button className={cls} onClick={() => { setCls((cls) => (cls === "red" ? "green" : "red")); setIsListening(prevState => !prevState); }}>
                            <FaMicrophone style={{ color: 'black' }} />
                        </button>
                        <input
                            placeholder="Send a message..."
                            onKeyPress={keyPressHanlder}
                            type="text"
                            value={note}
                        />
                        <button className='send' style={{ backgroundColor: 'transparent' }} onClick={onClicksHanlder} disabled={!note}>
                            <IoSend style={{ color: '#F05454', width: '40px', fontSize: '2em' }} />
                        </button>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default DigitalHuman;
