import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useAppSelector } from "../hooks/useAppSelector";
import { useContext, useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import DOMPurify from "dompurify";
import Dynamictext from "./Dynamictext";
import '../App.css';
import ai_icon from '../assets/images/ai.png';
import copy_icon from '../assets/images/copy.png';
import regenerate_icon from '../assets/images/regenerate.png';
import like_icon from '../assets/images/like.png';
import dislike_icon from '../assets/images/dislike.png';
import like_neutral_icon from '../assets/images/like-neutral.png';
import dislike_neutral_icon from '../assets/images/dislike-neutral.png';
import { apiEndpoint } from "../constants";
import { useAppDispatch } from "../hooks/useAppDispatch";
import { addMessage, reactMessage } from "../store/slices/messageSlice";
import Transitiondiv from "./Transitiondiv";
import Form from "./Form";
import { Appcontext } from "../contexts/AppContext";
import { preSanitizeContent, serverRequest, toRgba } from "../utils";
import Lineloader from "./Lineloader";
const Template = (props) => {
    //actions- data-collection
    const agent = useAppSelector((state) => state.agent);
    const messages = useAppSelector((state) => state.messages);
    const templates = useRef([
        { id: "conversation", component: Conversation },
        { id: "fetching", component: Fetching },
        { id: "data-collection", component: Datacollector }
    ]).current;
    let Component = templates.find((item) => item.id == props.template)?.component;
    const dispatch = useAppDispatch();
    const appContext = useContext(Appcontext);
    const react = async (id, reaction) => {
        dispatch(reactMessage({ id: props.id, data: reaction }));
        const res = await fetch(apiEndpoint + "/reaction", {
            headers: {
                'Content-Type': "application/json"
            },
            method: "PUT",
            body: JSON.stringify({
                "messageId": id,
                "reaction": reaction
            })
        });
        const resData = await res.json();
    };
    const regenerateMessage = () => {
        props.eventHandler({ name: "send-message", data: props.data.query });
    };
    const copyMessage = () => {
        navigator.clipboard.writeText(props.data.content);
    };
    return (_jsxs("div", { className: "avamodule-template-wrapper", children: [_jsx("div", { className: "avamodule-template-bodywrapper", style: { justifyContent: props.sender == "ava" ? "flex-start" : "flex-end" }, children: Component
                    ?
                        _jsx(Component, { eventHandler: props.eventHandler, sender: props.sender, data: props.data, messages: messages.data, agent: agent.data, theme: appContext?.theme })
                    :
                        null }), _jsx("div", { className: "avamodule-template-footerwrapper", style: { justifyContent: props.sender == "ava" ? "flex-start" : "flex-end", gap: "5px" }, children: props.sender == "ava"
                    ?
                        _jsxs(_Fragment, { children: [props.data?.query
                                    ?
                                        _jsx(Transitiondiv, { wrapperStyles: { display: "flex" }, type: "in", effect: "pop", children: _jsxs("div", { className: "avamodule-template-actionswrapper", style: { display: (props.sender == "ava" && props.template == "conversation") ? "flex" : "none" }, children: [!props.reaction
                                                        ?
                                                            _jsxs(_Fragment, { children: [_jsx("button", { onClick: () => react(props.id, "like"), style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: like_neutral_icon, className: 'avamodule-action-icon' }) }), _jsx("button", { onClick: () => react(props.id, "dislike"), style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: dislike_neutral_icon, className: 'avamodule-action-icon' }) })] })
                                                        :
                                                            _jsx("button", { style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { className: 'avamodule-action-icon', src: props.reaction == "like" ? like_icon : dislike_icon }) }), _jsx("button", { onClick: regenerateMessage, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: regenerate_icon, className: 'avamodule-action-icon' }) }), _jsx("button", { onClick: copyMessage, style: { backgroundColor: 'transparent', border: "none", padding: 0 }, children: _jsx("img", { src: copy_icon, className: 'avamodule-action-icon' }) })] }) })
                                    :
                                        null, _jsx("p", { className: "avamodule-message-createdat", children: new Date(props.createdAt).toLocaleTimeString().substring(0, 5) })] })
                    :
                        _jsx(_Fragment, { children: _jsx("p", { className: "avamodule-message-createdat", children: new Date(props.createdAt).toLocaleTimeString().substring(0, 5) }) }) })] }));
};
export default Template;
const Conversation = (props) => {
    const preSanitizedContent = preSanitizeContent(props.data.content);
    const sanitizedContent = DOMPurify.sanitize(preSanitizedContent.conversation);
    const theme = props.theme;
    const followUpQuestions = preSanitizedContent.followupQuestions;
    const sendMessage = (query) => {
        console.log("Query", JSON.stringify({ query: query.trim() }));
        props.eventHandler({ name: "send-message", data: query });
    };
    //console.log(JSON.stringify({Content:preSanitizedContent},null,2))
    return (_jsxs("div", { className: "avamodule-template-conversations-wrapper", children: [_jsx("div", { style: { ...{ borderRadius: "18px", padding: "10px", width: "100%", boxSizing: "border-box", backgroundColor: (props.sender == "ava" ? theme?.avaMessageBox.backgroundColor : theme.clientMessageBox.backgroundColor) }, ...(props.sender == "ava" ? { borderTopLeftRadius: "3px" } : { borderTopRightRadius: "3px" }) }, children: _jsx(ReactMarkdown, { className: "avamodule-message-content", components: {
                        a: ({ href, children, ...rest }) => (_jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: "avamodule-message-content", style: { color: props.sender == "ava" ? theme.avaMessageBox.textColor : theme.clientMessageBox.textColor }, ...rest, children: children })),
                        p: ({ node, ...rest }) => _jsx("span", { className: "avamodule-message-content", ...rest, style: { color: props.sender == "ava" ? theme.avaMessageBox.textColor : theme.clientMessageBox.textColor } })
                    }, children: sanitizedContent }) }), followUpQuestions && followUpQuestions.length > 0
                ?
                    _jsx("div", { className: "avamodule-followupquestions-wrapper", children: followUpQuestions.map((item) => item
                            ?
                                _jsx(Transitiondiv, { effect: "pop", children: _jsx("button", { onClick: () => sendMessage(item), className: "avamodule-followupquestions-item-wrapper", style: { backgroundColor: (toRgba(theme.avaMessageBox.backgroundColor, 0.4)) }, children: _jsx("p", { className: "avamodule-message-content", style: { textAlign: "start", whiteSpace: "nowrap", padding: "2px" }, children: item }) }) })
                            :
                                null) })
                :
                    null] }));
};
const Fetching = (props) => {
    const theme = props.theme; //props.agent?.appearance?props.agent.appearance:defaultTheme
    const wrapperRef = useRef(undefined);
    const [width, setWidth] = useState();
    const timer = useRef(undefined);
    useEffect(() => {
        timer.current ? clearInterval(timer.current) : null;
        timer.current = setInterval(() => {
            wrapperRef.current ? console.log("Dim", wrapperRef.current.getBoundingClientRect().width) : null;
            if (wrapperRef.current && wrapperRef.current.getBoundingClientRect().width != 0) {
                setWidth(wrapperRef.current.getBoundingClientRect().width);
                //clearInterval(timer.current)
            }
        }, 100);
        // const updateWidth = () => {
        //   if (wrapperRef.current) {
        //     setWidth(wrapperRef.current.getBoundingClientRect().width);
        //   }
        // };
        // // Create a ResizeObserver to watch size changes
        // const resizeObserver = new ResizeObserver(() => {
        //   updateWidth();
        //   console.log("Resize");
        // });
        // if (wrapperRef.current) {
        //   resizeObserver.observe(wrapperRef.current);
        //   updateWidth(); // Initial width
        // }
        // Cleanup observer on unmount
        return () => {
            clearInterval(timer.current);
            //resizeObserver.disconnect();
        };
    }, []);
    return (_jsxs("div", { style: { display: "flex", width: "100%", boxSizing: "border-box", flexDirection: 'row', alignItems: 'center', gap: "10px", borderRadius: "18px", padding: "10px" }, children: [_jsx("img", { className: "avamodule-sadface", src: ai_icon }), _jsxs("div", { ref: wrapperRef, style: { display: "flex", flexDirection: 'column', gap: "10px" }, children: [props.agent.business?.facts && props.agent.business?.facts?.length > 0
                        ?
                            _jsx(Dynamictext, { timePeriod: 4000, style: { margin: 0, fontFamily: "Neutrif-Regular_Italic" }, list: props.agent.business.facts.map((fact) => ("' " + fact + " '")) })
                        :
                            null, _jsx(Lineloader, { height: 2, width: width ? width : 0, color: { left: theme.clientMessageBox.backgroundColor, right: theme.avaMessageBox.backgroundColor, mask: "#ffffff" }, timePeriod: 1000 })] })] }));
};
const Datacollector = (props) => {
    const dispatch = useAppDispatch();
    const eventHandler = async (e) => {
        switch (e.name) {
            case "submit":
                let res = await serverRequest({
                    url: "https://chatapi.campusroot.com/trigger", //props.data.submitEndpoint,
                    reqType: "POST",
                    routeType: "public",
                    body: { actionId: props.data.actionId, conversationId: props.data.conversationId, collectedData: e.data.map((item) => ({ key: item.id, data: item.data, fieldPath: props.data.dataSchema.find((item2) => item2.key == item.id)?.fieldPath })) }
                });
                if (res.success) {
                    let res2 = await serverRequest({
                        url: res.data.url,
                        reqType: res.data.method,
                        routeType: res.data.accessType.toLowerCase(),
                        body: res.data.body,
                    });
                    if (res2.success) {
                        dispatch(addMessage({
                            id: new Date().getTime().toString(),
                            template: "conversation",
                            data: { content: res2.message },
                            sender: "ava",
                            createdAt: new Date().toISOString()
                        }));
                    }
                    if (res2.data.AccessToken) {
                        localStorage.setItem("access_token", res2.data.AccessToken);
                    }
                }
                break;
        }
    };
    return (_jsxs("div", { style: { display: 'flex', flex: 1, flexDirection: "column", gap: "10px" }, children: [_jsx("p", { className: "avamodule-data-collection-title", children: "Please let me know the following details" }), _jsx(Form, { eventHandler: eventHandler, initialState: props.data.dataSchema.filter((item) => item.data).map((item) => ({ id: item.key, data: item.data })), dataSchema: props.data.dataSchema })] }));
};
const Confirmation = (props) => {
    const yes = () => {
    };
    const no = () => {
    };
    const edit = () => {
    };
    return (_jsxs("div", { children: [_jsx("p", {}), _jsx(Transitiondiv, { wrapperStyles: { alignSelf: "flex-end" }, effect: "pop", type: "in", children: _jsx("button", { className: "button-dark", style: { alignSelf: "flex-end" }, onClick: yes, children: _jsx("p", { className: "nextbutton-text", children: "Edit Data" }) }) }), _jsx(Transitiondiv, { wrapperStyles: { alignSelf: "flex-end" }, effect: "pop", type: "in", children: _jsx("button", { className: "button-dark", style: { alignSelf: "flex-end" }, onClick: no, children: _jsx("p", { className: "nextbutton-text", children: "Yes" }) }) }), _jsx(Transitiondiv, { wrapperStyles: { alignSelf: "flex-end" }, effect: "pop", type: "in", children: _jsx("button", { className: "button-dark", style: { alignSelf: "flex-end" }, onClick: edit, children: _jsx("p", { className: "nextbutton-text", children: "No" }) }) })] }));
};
//# sourceMappingURL=Template.js.map