import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import '../App.css';
import '../scroll.css';
import { useRef, useEffect, useState, useContext } from "react";
import ava_icon from '../assets/images/logo-new.png';
import clear_icon from '../assets/images/clear.png';
import loading_ava_gif from '../assets/images/loading_ava.gif';
import 'regenerator-runtime';
import { apiEndpoint, defaultTheme } from "../constants";
import { chunksExtractor, getLocation, toRgba } from "../utils";
import { useAppSelector } from '../hooks/useAppSelector';
import Template from './Template';
import { useAppDispatch } from '../hooks/useAppDispatch';
import { addMessage, addMessageChunk, removeMessage, resetMessages, setMessages, updateMessage } from '../store/slices/messageSlice';
import Messageinput from './Messageinput';
import { setAgent } from '../store/slices/agentSlice';
import Transitiondiv from './Transitiondiv';
import Stackscreen from './Stackscreen';
import { Stackscreencontext } from '../contexts/Stackscreencontext';
import store from '../store/index';
import { Appcontext } from '../contexts/AppContext';
import Avainteractive from './Avainteractive';
import { initiateChatSocketConnection } from '../socket';
const Ava = (props) => {
    const [setup, setSetup] = useState(props.functionMode == "functional" ? false : true);
    const dispatch = useAppDispatch();
    const Context = useContext(Appcontext);
    const agent = useAppSelector((state) => state.agent);
    const [userLocation, setUserLocation] = useState();
    useEffect(() => {
        if (props.functionMode == "functional" || props.functionMode == "avakado") {
            let agentId = props.agentId;
            if ((!agentId) || agentId?.length == 0) {
                dispatch(updateMessage({
                    id: new Date().getTime().toString(),
                    template: "conversation",
                    data: { content: "Oops! Invalid Agent Id", query: "" },
                    sender: "ava",
                    createdAt: new Date().toISOString()
                }));
            }
            else {
                setSetup(false);
                getAgent(agentId).then((res) => res.json().then((data) => {
                    console.log("Response agent", JSON.stringify(data, null, 2));
                    if (data.success) {
                        dispatch(setAgent({
                            requestStatus: "not_initiated",
                            responseStatus: "not_recieved",
                            haveAnIssue: false,
                            issue: "",
                            data: data.data
                        }));
                    }
                    else {
                        dispatch(addMessage({
                            id: new Date().getTime().toString(),
                            template: "conversation",
                            data: { content: "Oops! " + data.message, query: "" },
                            sender: "ava",
                            createdAt: new Date().toISOString()
                        }));
                    }
                    setSetup(true);
                }));
            }
        }
    }, [props.agentId]);
    const getAgent = async (agentId) => {
        let res = await fetch(apiEndpoint + "/get-agent?agentId=" + agentId, {
            method: "GET"
        });
        return res;
    };
    useEffect(() => {
        getLocation().then((data) => setUserLocation(data));
        return () => {
            dispatch(resetMessages(null));
        };
    }, []);
    return (_jsx(Appcontext.Provider, { value: { userLocation: userLocation, theme: ((props.functionMode == "functional" || props.functionMode == "avakado") ? (agent.data?.appearance ?? defaultTheme) : (props.config?.appearance ?? defaultTheme)) }, children: _jsx("div", { className: 'avamodule-app-wrapper-' + props.layoutMode, children: !setup
                ?
                    _jsxs("div", { className: 'avamodule-setup-wrapper', children: [_jsx("img", { src: loading_ava_gif, className: 'avamodule-ava-loader' }), _jsx("div", { style: { display: 'flex', flexDirection: "row", alignItems: 'center', gap: "10px" }, children: _jsx("span", { className: 'avamodule-hi', children: "Getting everything ready for you! Hang tight\u2026!" }) })] })
                :
                    _jsx(Stackscreen, { screens: [
                            { id: "1", component: Chatwindow, data: { functionMode: props.functionMode, config: props.config } },
                        ] }) }) }));
};
const Chatwindow = (props) => {
    const messages = useAppSelector((state) => state.messages).data;
    const agent = useAppSelector((state) => state.agent);
    const appContext = useContext(Appcontext);
    const scrollRef = useRef(null);
    const conversationId = useRef(null);
    const socketJoined = useRef(false);
    const getCurrentMessages = () => messages;
    const dispatch = useAppDispatch();
    const stopRecieving = useRef([]);
    const [message, setMessage] = useState("");
    const stackContext = useContext(Stackscreencontext);
    const dataSchemas = useRef({
        short: [
            {
                label: "Name",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Emailid",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Mobile",
                type: "number",
                required: true,
                comments: "",
                validator: ""
            }
        ],
        long: [
            {
                label: "Name",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Emailid",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Mobile",
                type: "number",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Address",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            },
            {
                label: "Requirement",
                type: "string",
                required: true,
                comments: "",
                validator: ""
            }
        ]
    }).current;
    const message_send = async (msg) => {
        if (msg.length > 0) {
            dispatch(addMessage({
                id: new Date().getTime().toString(),
                template: "conversation",
                data: { content: msg },
                sender: "user",
                createdAt: new Date().toISOString()
            }));
            setTimeout(() => {
                var loadingMsgId = new Date().getTime().toString();
                dispatch(addMessage({
                    id: loadingMsgId,
                    template: "fetching",
                    data: { facts: agent.data?.personalInfo.facts },
                    sender: "ava",
                    createdAt: new Date().toISOString()
                }));
                //console.log("User Location",JSON.stringify(appContext?.userLocation,null,2));
                apiRequest(messages, msg, loadingMsgId, appContext?.userLocation);
            }, 500);
        }
        else {
            alert("Enter a message");
        }
    };
    const apiRequest = async (allMessages, message, loadId, userLocation) => {
        let res = await fetch(apiEndpoint, {
            headers: {
                'Content-Type': "application/json"
            },
            body: JSON.stringify({
                userMessage: message,
                browserUrl: window.location.href,
                geoLocation: userLocation,
                conversationId: conversationId.current,
                agentId: agent.data?._id,
                //channelId:,
                streamOption: true
            }),
            method: "POST"
        });
        const reader = res?.body?.getReader();
        const decoder = new TextDecoder("utf-8");
        if (reader) {
            dispatch(removeMessage(loadId));
            let partialChunk = null;
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                const text = decoder.decode(value, { stream: true });
                let chunks = chunksExtractor(text, partialChunk);
                (chunks && chunks.length > 0 && chunks[0].conversationId && !conversationId.current) ? conversationId.current = chunks[0].conversationId : null;
                chunks.filter((item) => item.id != "partial-chunk").forEach((item) => {
                    handleChunks(item, message);
                });
                if (chunks.find((item) => item.id == "end")) {
                    break;
                }
                //define partial chunk
                partialChunk = chunks.find((item) => item.id == "partial-chunk") ?? null;
                // let msgRecieved=chunks.reduce((acc:any,curr:any)=>acc+(curr.chunk!="__malformed-chunk__"?curr.chunk:"....."),"");
                // if(messageId)
                // {
                //     dispatch(addMessageChunk({id:messageId,data:msgRecieved}))
                // }
                // else
                // {
                //     messageId=(chunks && chunks.length>0)?chunks[0].messageId:null;
                //     if(messageId)
                //     {
                //         dispatch(addMessage({
                //             id:messageId,
                //             template:"conversation",
                //             data:{content:msgRecieved,query:message},
                //             sender:"ava",
                //             createdAt:new Date().toISOString()
                //         }))
                //     }
                // }
                // if(malformedChunk || noInfoChunk)
                // {
                //     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", conversationId: chunk.conversationId, dataSchema: chunk.data.dataSchema, query: query },
                    sender: "ava",
                    createdAt: new Date().toISOString()
                }));
                // if(chunk.data.action.workingData.bod.length<=3){
                //     dispatch(addMessage({
                //         id:new Date().getTime().toString(),
                //         template:"data-collection",
                //         data:{actionId:chunk.data.action._id,submitEndpoint:"",title:"Appointment",dataSchema:chunk.data.action.dataSchema,query:query},
                //         sender:"ava",
                //         createdAt:new Date().toISOString()
                //     }))
                // }
                // else
                // {
                //    // stackContext
                // }
                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;
        }
    };
    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
        if (conversationId.current && !socketJoined.current && agent.data?._id && agent.data.business) {
            //join socket
            // let triggerObj={
            //     action:"join",
            //     data:{
            //         conversationID:conversationId,
            //         agentId:agent.data?._id
            //     }
            // }
            // getSocket().emit('trigger',triggerObj);
            //console.log("Conversation Id",conversationId.current);
            initiateChatSocketConnection(agent.data._id, conversationId.current, agent.data.business._id);
            socketJoined.current = true;
        }
    }, [messages]);
    useEffect(() => {
        if (props.data.functionMode == "design") {
            dispatch(setMessages([
                {
                    id: new Date().getTime().toString(),
                    template: "conversation",
                    data: { content: "This the query you ask!" },
                    sender: "user",
                    createdAt: new Date().toISOString()
                },
                {
                    id: new Date().getTime().toString(),
                    template: "conversation",
                    data: { content: "This is the response from AVA!", query: "This the query you ask!" },
                    sender: "ava",
                    createdAt: new Date().toISOString()
                }
            ]));
        }
        if (props.data.functionMode == "avakado") {
            dispatch(addMessage({
                id: "ava-1",
                template: "conversation",
                data: { content: "Hie I am **AVA**, your AI agent!Designed to adapt to your needs.  \n **You can train me** with your own knowledge, connect me to your website, upload documents, or even feed me your YouTube videos.  \n**I can make network calls**, fetch data, and integrate seamlessly with your systems to automate tasks.  \n**Customize my look**, change my colors, and match my chat style to your brand." },
                sender: "ava",
                createdAt: new Date().toISOString()
            }));
            setTimeout(() => {
                dispatch(addMessage({
                    id: "ava-2",
                    template: "conversation",
                    data: { content: "Feel free to ask me anything here!", query: "" },
                    sender: "ava",
                    createdAt: new Date().toISOString()
                }));
            }, 1500);
        }
    }, []);
    const handleQuickQuestion = (question) => {
        message_send(question.label);
    };
    const messageInputEventHandler = (e) => {
        //console.log("Event Raised AVA-Module",JSON.stringify(e,null,2))
        switch (e.name) {
            case "send-message":
                message_send(e.data);
                break;
            case "start-recording":
                //setEnableRecording(true)
                break;
            case "stop-recording":
                //setEnableRecording(false)
                break;
        }
    };
    useEffect(() => {
        setTimeout(() => {
            //simulateDataCollector()
            ///simulateNetworkRequest()
            //stackContext?stackContext?.screensHandler({type:"add",payload:{id:"2",component:Dummy}}):null;
        }, 2000);
    }, []);
    const templateEventHandler = (e) => {
        //console.log("Event Raised AVA-Module",JSON.stringify(e,null,2))
        switch (e.name) {
            case "send-message":
                message_send(e.data);
                break;
        }
    };
    const simulateDataCollector = () => {
        let temp = "full";
        let dataCollectionChunk = {
            id: "data-collection", //conversation|data-collection|confirmation|end
            messageId: "1234",
            conversationId: "123",
            responseType: temp,
            data: {
                actionId: "12345",
                submitEndpoint: apiEndpoint + "/actionUpdate",
                dataSchema: [
                    {
                        label: "Name",
                        type: "string",
                        required: true,
                        comments: "",
                        validator: "",
                        // value:""
                    },
                    {
                        label: "Emailid",
                        type: "string",
                        required: true,
                        comments: "",
                        validator: "",
                        //value:""
                    },
                    {
                        label: "Mobile",
                        type: "number",
                        required: true,
                        comments: "",
                        validator: "",
                        //value:""
                    }
                ]
            }
        };
        handleChunks(dataCollectionChunk, "Hie");
    };
    const simulateNetworkRequest = () => {
        let temp = "full";
        let dummySchema = [
            {
                label: "Name",
                type: "string",
                required: true,
                comments: "",
                validator: "",
                // value:""
            },
            {
                label: "Emailid",
                type: "string",
                required: true,
                comments: "",
                validator: "",
                //value:""
            },
            {
                label: "Mobile",
                type: "number",
                required: true,
                comments: "",
                validator: "",
                //value:""
            }
        ];
        let dummyAction = {
            _id: "12345",
            name: "dummy",
            intent: "Book Appointment",
            accessType: "Private",
            dataSchema: dummySchema,
            // auth?:{ 
            //     endpoint: string, 
            //     dataSchema: DataSchema[]
            // },
            configData: {
                //id: string, 
                token: "jhncjhnd2kjnjcnjincijniw3ndncisdnic"
            },
            workingData: {
                url: "https://www.clientcrm.com/api/add-client",
                headers: "",
                //body:any,
                method: "POST"
            }
        };
        handleChunks({
            id: "network-request", //conversation|data-collection|confirmation|end
            messageId: "1234",
            conversationId: "123",
            responseType: temp,
            data: { action: dummyAction, data: { Name: "Rohith", EmailId: "Name@gmail.com", Mobile: "9999999999" } }
        }, "Hie");
    };
    return (_jsx("div", { className: 'avamodule-ava-wrapper', children: _jsxs("div", { className: 'avamodule-ava-subwrapper', children: [_jsxs("div", { className: 'avamodule-header', children: [_jsx(Avainteractive, { eyeWidth: 7 }), _jsxs("div", { style: { flex: 1 }, children: [_jsx("span", { className: 'avamodule-title', children: "AVA" }), props.data.functionMode != "avakado"
                                    ?
                                        _jsx("div", { style: { display: "flex", flexDirection: "row", alignItems: "center", gap: "5px" }, children: _jsx("span", { className: 'avamodule-university-name', children: agent.data?.business.name }) })
                                    :
                                        null] }), agent.data?.business?.logoURL
                            ?
                                _jsx("img", { className: 'avamodule-general-icon', style: { borderRadius: "100px" }, src: agent.data.business.logoURL })
                            :
                                null, _jsx("button", { onClick: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? () => dispatch(resetMessages(null)) : () => { }, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: clear_icon, className: 'avamodule-general-icon' }) })] }), _jsx("div", { ref: scrollRef, className: 'avamodule-messages-wrapper', children: messages.length == 0
                        ?
                            _jsxs("div", { className: 'avamodule-intro-wrapper', children: [_jsx("img", { src: ava_icon, className: 'avamodule-logo' }), _jsx("span", { className: 'avamodule-hi', children: agent.data?.personalInfo.welcomeMessage ? agent.data.personalInfo.welcomeMessage : "Hie! I am AVA" }), _jsx("div", { className: 'avamodule-quickquestions-wrapper', children: agent.data?.personalInfo?.quickQuestions?.slice(0, 4).map((q) => _jsx("button", { onClick: (props.data.functionMode == "functional" || props.data.functionMode == "avakado") ? () => handleQuickQuestion(q) : () => { }, className: 'avamodule-quickquestion-wrapper', style: { backgroundColor: agent.data?.appearance ? toRgba(agent.data.appearance.clientMessageBox.backgroundColor, 0.2) : toRgba(defaultTheme.clientMessageBox.backgroundColor, 0.2) }, children: _jsx("span", { className: 'avamodule-quickquestion-label', children: q.label }) })) })] })
                        :
                            messages.map((msg) => _jsx(Transitiondiv, { wrapperStyles: { width: "100%", display: "flex" }, effect: "pop", children: _jsx(Template, { eventHandler: templateEventHandler, ...msg }, msg.id) })) }), _jsx(Messageinput, { data: { theme: appContext?.theme, functionMode: props.data.functionMode }, eventHandler: messageInputEventHandler })] }) }));
};
export default Ava;
{ /* <Message eventHandler={eventHandler} {...msg} agent={agent} client={client} theme={theme}/> */ }
//# sourceMappingURL=Ava.js.map