import { FluentButton } from "../UI/inputs/buttons/FluentButton.mjs";
import { ConfigService } from "../configService/index.mjs";
import { useUser } from "../utilities/auth/useUser.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { AmbientTextField } from "../UI/inputs/textField/AmbientTextField.mjs";
import { ChatMessage } from "./ChatMessage.mjs";
import { useChatBot } from "../utilities/chatBot/useChatBot.mjs";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Link, Typography } from "@material-ui/core";
import { useSnackbar } from "notistack";
import { useTranslation } from "react-i18next";
import { makeStyles as makeStyles$1 } from "@material-ui/core/styles";
//#region src/chatBot/ChatContainer.jsx
const useStyles = makeStyles$1((theme) => ({
	loadingContainer: {
		display: "inline-block",
		fontSize: "2em"
	},
	pulseEllipsis: {
		display: "inline-block",
		animation: "$pulse 1.5s infinite",
		"&:nth-of-type(2)": { animationDelay: "0.5s" },
		"&:nth-of-type(3)": { animationDelay: "1s" }
	},
	"@keyframes pulse": {
		"0%": {
			transform: "scale(1)",
			opacity: .6
		},
		"50%": {
			transform: "scale(1.2)",
			opacity: 1
		},
		"100%": {
			transform: "scale(1)",
			opacity: .6
		}
	}
}));
const ChatContainer = (props) => {
	const classes = useStyles();
	const { messageHistory, addMessage, removeMessageHistory, removeLoadingMessage } = useChatBot();
	const user = useUser();
	const [newMessageContent, setNewMessageContent] = useState("");
	const messageEndRef = useRef(null);
	const productId = ConfigService.config.UNITY_PRODUCT_ID;
	const aiSearchUrl = ConfigService.config.AI_SEARCH_URL;
	const aiSearchIndexName = ConfigService.config.AI_SEARCH_INDEX_NAME;
	const aiSearchKey = ConfigService.config.AI_SEARCH_KEY;
	const udpAiApiBase = ConfigService.config.UDPAI_API_BASE;
	const { enqueueSnackbar } = useSnackbar();
	const { t } = useTranslation();
	const handleSendMessage = async () => {
		addMessage(newMessageContent, {
			...user,
			name: "You"
		}, newMessageContent);
		setNewMessageContent("");
		addLoadingMessage();
		try {
			await sendMessage(newMessageContent, addMessage);
			removeLoadingMessage();
		} catch (error) {
			console.error("Error sending message:", error);
		}
	};
	const handleNewSession = async () => {
		try {
			await removeMessageHistory();
			enqueueSnackbar(t(`Chat Session Cleared`), {
				variant: "success",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		} catch (error_0) {
			console.error("Error create new chat session:", error_0);
		}
	};
	const addLoadingMessage = () => {
		addMessage(/* @__PURE__ */ React.createElement("div", { className: classes.loadingContainer }, /* @__PURE__ */ React.createElement("span", { className: classes.pulseEllipsis }, "."), /* @__PURE__ */ React.createElement("span", { className: classes.pulseEllipsis }, "."), /* @__PURE__ */ React.createElement("span", { className: classes.pulseEllipsis }, ".")), {
			name: "AI Assistant",
			loading: true
		}, "");
	};
	useEffect(() => {
		messageEndRef.current?.scrollIntoView({ behavior: "smooth" });
	}, [messageHistory]);
	const formatCitations = (citations) => {
		return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("ol", null, citations.map((citation) => {
			return /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement(Link, {
				href: citation.url,
				target: "_blank",
				rel: "noopener"
			}, /* @__PURE__ */ React.createElement(Typography, {
				variant: "body2",
				style: { whiteSpace: "pre-line" }
			}, citation.title)));
		})));
	};
	const parseAiResponse = (response, addMessage_0) => {
		try {
			const gptResponseMessage = response.data.LLMResponse.choices[0].message;
			const messageText = gptResponseMessage.content;
			const citations_0 = gptResponseMessage.context.citations;
			const showCitations = messageText.toString().includes("[doc");
			const textContent = messageText.toString().replaceAll("[doc", "[");
			addMessage_0(/* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { style: { wordWrap: "break-word" } }, /* @__PURE__ */ React.createElement(Typography, {
				variant: "body2",
				style: { whiteSpace: "pre-line" }
			}, textContent)), citations_0.length > 0 && showCitations && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("br", null), /* @__PURE__ */ React.createElement(Typography, {
				variant: "body2",
				style: { whiteSpace: "pre-line" }
			}, "Refer to the XWiki documents for more info:"), formatCitations(citations_0))), { name: "AI Assistant" }, textContent);
		} catch (e) {
			const errorMessage = "Sorry, an error has occurred.";
			addMessage_0(errorMessage, { name: "AI Assistant" }, errorMessage);
		}
	};
	const executeQuery = useCallback(async (data, aiModelId) => apiMutate(udpAiApiBase, `aiservice/llm`, {
		method: "post",
		headers: { currentProductId: productId }
	}, data), [productId, udpAiApiBase]);
	const sendMessage = async (newMessageContent_0, addMessage_1) => {
		parseAiResponse(await executeQuery({ data: {
			modelName: "gpt-4o",
			useCache: "false",
			payload: {
				max_tokens: 4096,
				temperature: .5,
				n: 1,
				presence_penalty: 0,
				messages: [
					{
						role: "system",
						content: "You are an assistant helping a user using existing knowledge supplemented by additional data."
					},
					...messageHistory.map((item) => ({
						role: item.createdBy.name === "AI Assistant" ? "assistant" : item.createdBy.name === "You" ? "user" : item.createdBy.name,
						content: item.messageText
					})),
					{
						role: "user",
						content: newMessageContent_0
					}
				],
				data_sources: [{
					type: "azure_search",
					parameters: {
						endpoint: aiSearchUrl,
						semantic_configuration: aiSearchIndexName,
						query_type: "semantic",
						in_scope: false,
						strictness: 1,
						top_n_documents: 5,
						authentication: {
							type: "api_key",
							key: aiSearchKey
						},
						index_name: aiSearchIndexName,
						filter: `Products/any(p: p eq '${productId}')`
					}
				}]
			}
		} }), addMessage_1);
	};
	return /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		height: "100%"
	} }, /* @__PURE__ */ React.createElement(FluentButton, {
		id: "udpRecord-ChatContainer-NewSession",
		onClick: handleNewSession
	}, "Clear Chat"), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		gap: "10px",
		padding: "3px",
		height: "100%",
		overflowY: "auto",
		flexGrow: 1
	} }, messageHistory.map((message, index) => /* @__PURE__ */ React.createElement(ChatMessage, {
		key: index,
		message
	})), /* @__PURE__ */ React.createElement("div", { ref: messageEndRef })), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		marginTop: "5px",
		position: "sticky",
		bottom: 0,
		padding: "3px",
		zIndex: 1,
		background: "white"
	} }, /* @__PURE__ */ React.createElement("div", { style: { flexGrow: 1 } }, /* @__PURE__ */ React.createElement(AmbientTextField, {
		id: "udpRecord-ChatContainer-Enter",
		multiline: true,
		value: newMessageContent,
		onChange: (e_0) => setNewMessageContent(e_0.target.value),
		onKeyDown: (e_1) => {
			if (e_1.key === "Enter" && !e_1.shiftKey) {
				e_1.preventDefault();
				handleSendMessage();
			}
		}
	})), /* @__PURE__ */ React.createElement(FluentButton, {
		id: "udpRecord-ChatContainer-Send",
		onClick: handleSendMessage,
		autoFocus: true,
		variant: "outlined"
	}, "Send")));
};
//#endregion
export { ChatContainer };

//# sourceMappingURL=ChatContainer.mjs.map