import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Appcontext } from "../contexts/AppContext";
import { Stackscreencontext } from "../contexts/Stackscreencontext";
import { useAppDispatch } from "../hooks/useAppDispatch";
import { useAppSelector } from "../hooks/useAppSelector";
import { useContext, useEffect, useRef, useState } from "react";
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
import record_icon from '../assets/images/record.png';
import send_icon from '../assets/images/send.png';
import stop_icon from '../assets/images/stop.png';
import { AvalitePlaceholders, apiEndpoint } from "../constants";
import Dynamictext from "./Dynamictext";
import ai_icon from '../assets/images/ai.png';
import '../App.css';
import '../avalite.css';
import store from "../store/index";
import { addMessage, addMessageChunk, setMessages, updateMessage } from "../store/slices/messageSlice";
import { chunksExtractor } from "../utils";
import ReactMarkdown from "react-markdown";
import DOMPurify from "dompurify";
import Lineloader from "./Lineloader";
const Avalite = (props) => {
    const messages = useAppSelector((state) => state.messages).data;
    const agent = useAppSelector((state) => state.agent);
    //const [message,setMessage]=useState("");
    const [mode, setMode] = useState("blur");
    const [loading, setLoading] = useState(false);
    const stackContext = useContext(Stackscreencontext);
    const appContext = useContext(Appcontext);
    const conversationId = useRef(null);
    const getCurrentMessages = () => messages;
    const dispatch = useAppDispatch();
    const wrapperRef = useRef(null);
    const loaderWrapperRef = useRef(null);
    const messageInputEventsHandler = (e) => {
        switch (e.name) {
            case "send-message":
                console.log("Sending", e.data);
                message_send(e.data);
                break;
            case "focus":
                setMode("focus");
                break;
            case "blur":
                setMode("blur");
                break;
        }
    };
    const apiRequest = async (message, userLocation) => {
        let res = await fetch(apiEndpoint + "/v1/agent", {
            headers: {
                'Content-Type': "application/json"
            },
            body: JSON.stringify({
                userMessage: message,
                geoLocation: userLocation,
                conversationId: conversationId.current,
                agentId: props.agentId,
                streamOption: true
            }),
            method: "POST"
        });
        const reader = res?.body?.getReader();
        const decoder = new TextDecoder("utf-8");
        setLoading(false);
        if (reader) {
            //dispatch(removeMessage(loadId))
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                const text = decoder.decode(value, { stream: true });
                let chunks = chunksExtractor(text, null);
                (chunks && chunks.length > 0 && chunks[0].conversationId && !conversationId.current) ? conversationId.current = chunks[0].conversationId : null;
                chunks.forEach((item) => {
                    handleChunks(item, message);
                });
                if (chunks.find((item) => item.id == "end")) {
                    break;
                }
            }
        }
    };
    const handleChunks = async (chunk, query) => {
        switch (chunk.id) {
            case "conversation":
                let messageId = store.getState().messages.data.find((item) => item.id == chunk.messageId)?.id;
                //console.log("Chunk Handle",store.getState().messages.data,chunk.data,chunk.messageId);
                if (messageId) {
                    if (chunk.responseType == "chunk") {
                        dispatch(addMessageChunk({ id: chunk.messageId, data: chunk.data }));
                    }
                    else {
                        dispatch(updateMessage({
                            id: chunk.messageId,
                            template: "conversation",
                            data: { content: chunk.data, query: query },
                            sender: "ava",
                            createdAt: new Date().toISOString()
                        }));
                    }
                }
                else {
                    dispatch(addMessage({
                        id: chunk.messageId,
                        template: "conversation",
                        data: { content: chunk.data, query: query },
                        sender: "ava",
                        createdAt: new Date().toISOString()
                    }));
                }
                break;
            case "data-collection":
                //console.log("")
                //data.actionId: “”,
                // data.intent:””,
                // data.confidence:0.8
                // data.dataSchema
                // dispatch(addMessage({
                //     id:new Date().getTime().toString(),
                //     template:"data-collection",
                //     data:{actionId:chunk.data.actionId,submitEndpoint:"",title:"Appointment",dataSchema:chunk.data.dataSchema,query:query},
                //     sender:"ava",
                //     createdAt:new Date().toISOString()
                // }))
                break;
            case "confirmation":
                break;
            case "network-request":
                // let actionData:AgentAction=chunk.data.action
                // var res:Promise<ServerResponse>;
                // switch(actionData.workingData?.method){
                //     case "POST":
                //         res=serverRequest({
                //             url:actionData.workingData.url,
                //             reqType:"POST",
                //             routeType:actionData.accessType=="Private"?"private":"public",
                //             body:chunk.data.data,
                //             accessToken:actionData.configData?.token
                //         })
                //         break;
                //     case "GET":
                //         let params=chunk.data.data?objectToQueryParams(chunk.data.data):undefined;
                //         res=serverRequest({
                //             url:actionData.workingData.url+(params?("?"+params):""),
                //             reqType:"GET",
                //             routeType:actionData.accessType=="Private"?"private":"public",
                //             accessToken:actionData.configData?.token
                //         })
                //         break;
                //     case "PUT":
                //         res=serverRequest({
                //             url:actionData.workingData.url+(actionData.configData?.id?("/"+actionData.configData.id):""),
                //             reqType:"PUT",
                //             routeType:actionData.accessType=="Private"?"private":"public",
                //             body:chunk.data.data,
                //             accessToken:actionData.configData?.token
                //         })
                //         break;
                // }
                break;
        }
    };
    const message_send = async (msg) => {
        if (msg.length > 0) {
            setLoading(true);
            setTimeout(() => {
                dispatch(addMessage({
                    id: new Date().getTime().toString(),
                    template: "conversation",
                    data: { content: msg },
                    sender: "user",
                    createdAt: new Date().toISOString()
                }));
                apiRequest(msg, appContext?.userLocation);
            }, 10);
        }
        else {
            alert("Enter a message");
        }
    };
    useEffect(() => {
        return () => { dispatch(setMessages([])); };
    }, []);
    return (_jsxs("div", { ref: wrapperRef, tabIndex: 0, onBlur: (e) => { if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
            setMode("blur");
        } }, className: "avalitemodule-ava-wrapper", children: [_jsx("div", { className: 'avalitemodule-quickquestions-wrapper', children: props.config.quickQuestions?.map((item) => _jsx("button", { onClick: () => !loading ? message_send(item.value) : null, className: 'avalitemodule-quickquestion-wrapper', style: { backgroundColor: item.color }, children: _jsx("p", { className: 'avalitemodule-quickquestion', children: item.value }) })) }), _jsxs("div", { className: "avalitemodule-ava-subwrapper", children: [_jsx("img", { src: ai_icon, className: 'avalitemodule-logo' }), _jsx("div", { style: { display: "flex", boxSizing: "border-box" }, children: mode == "blur"
                            ?
                                _jsx("button", { onClick: () => setMode("focus"), style: { cursor: "text", backgroundColor: "transparent", border: "none", width: "100%", height: "100%", display: "flex", justifyContent: "flex-start", padding: 0 }, children: _jsx(Dynamictext, { timePeriod: 4000, style: { margin: 0, color: "gray", fontFamily: "Neutrif-Regular_Italic", textAlign: "start" }, list: AvalitePlaceholders }) })
                            :
                                _jsx(Messageinput, { data: { functionMode: "functional" }, eventHandler: messageInputEventsHandler }) }), loading
                        ?
                            _jsxs("div", { ref: loaderWrapperRef, className: "avalitemodule-loader-wrapper", children: [_jsx("div", { style: { display: "flex", flex: 1, transform: "scaleX(-1)" }, children: _jsx(Lineloader, { timePeriod: 1000, color: { left: "rgb(98 167 214)", right: "rgba(0,0,0,0)", mask: "#ffffff" }, height: 2, width: loaderWrapperRef.current ? loaderWrapperRef.current.getBoundingClientRect().width / 2 : 0 }) }), _jsx("div", { style: { display: "flex", flex: 1 }, children: _jsx(Lineloader, { timePeriod: 1000, color: { left: "rgb(98,167,214)", right: "rgba(0,0,0,0)", mask: "#ffffff" }, height: 2, width: loaderWrapperRef.current ? loaderWrapperRef.current.getBoundingClientRect().width / 2 : 0 }) })] })
                        :
                            null, messages.filter((msg) => msg.sender == "ava").length > 0
                        ?
                            _jsx("div", { className: "avalitemodule-response-wrapper", children: _jsx(ReactMarkdown, { className: "avalitemodule-response", components: {
                                        a: ({ href, children, ...rest }) => (_jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: "avalitemodule-response", ...rest, children: children })),
                                        p: ({ node, ...rest }) => _jsx("p", { className: "avalitemodule-response", ...rest })
                                    }, children: DOMPurify.sanitize(messages.filter((msg) => msg.sender == "ava").pop()?.data.content.replace("DATAPOINT_NEXUS", "")) }) })
                        :
                            null] })] }));
};
const Messageinput = (props) => {
    const [value, setValue] = useState(props.initialState ? props.initialState : "");
    const [enabelRecording, setEnableRecording] = useState(false);
    const { transcript, browserSupportsSpeechRecognition } = useSpeechRecognition();
    const messageInputRef = useRef(null);
    const handleKeyDown = (event) => {
        if (!event.shiftKey && event.key === "Enter" && value.trim().length > 0) {
            send();
        }
    };
    const send = () => {
        setValue("");
        props.eventHandler({ name: "send-message", data: value });
    };
    useEffect(() => {
        if (enabelRecording && browserSupportsSpeechRecognition) {
            messageInputRef.current.focus = true;
            SpeechRecognition.startListening();
        }
        else {
            SpeechRecognition.stopListening();
        }
    }, [enabelRecording]);
    useEffect(() => {
        transcript.length > 0 ? setValue(transcript) : null;
    }, [transcript]);
    useEffect(() => {
        if (messageInputRef.current) {
            //messageInputRef.current.style.height = 'auto';
            //messageInputRef.current.style.height=messageInputRef.current.scrollHeight+"px"
        }
    }, [value]);
    useEffect(() => {
        if (messageInputRef.current) {
            messageInputRef.current.focus();
        }
    }, []);
    return (_jsxs("div", { className: "avalitemodule-messageinput-wrapper", children: [_jsx("textarea", { style: { display: "flex" }, readOnly: props.data.functionMode == "preview", rows: 1, ref: messageInputRef, value: value, onKeyDown: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? handleKeyDown : () => { }, onChange: (e) => setValue(e.target.value), className: 'avalitemodule-input' }), _jsxs("div", { className: "avalitemodule-messageinput-actions-wrapper", children: [_jsx("button", { onClick: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? () => setEnableRecording(true) : () => { }, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: record_icon, style: { width: !enabelRecording ? "auto" : "0px" }, className: 'avamodule-general-icon' }) }), _jsx("button", { onClick: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? () => setEnableRecording(false) : () => { }, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: stop_icon, style: { width: enabelRecording ? "auto" : "0px" }, className: 'avamodule-general-icon' }) }), _jsx("button", { onClick: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? send : () => { }, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: send_icon, style: { width: value.length > 0 ? "auto" : "0px" }, className: 'avamodule-general-icon' }) })] })] }));
};
export default Avalite;
//# sourceMappingURL=Avalite.js.map