import { Form } from "../utilities/form/Form.mjs";
import { Field } from "../utilities/form/Field.mjs";
import { ConfigService } from "../configService/index.mjs";
import { useUser } from "../utilities/auth/useUser.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { FluentTextFieldAutoComplete } from "../UI/inputs/textField/FluentTextFieldAutoComplete.mjs";
import { SideSheet } from "../UI/surfaces/SideSheet.mjs";
import { useAxiosGet } from "../utilities/useAxiosGet.mjs";
import { PrimaryActionHeader } from "../UI/utilityDisplay/utilityHeader/PrimaryActionHeader.mjs";
import { PageContainer } from "../page/PageContainer/PageContainer.mjs";
import { useWorkflowStore } from "../stores/workflowStore.mjs";
import { UnitStateType } from "../enums/workflowEnums.mjs";
import { WorkflowTaskFlow } from "./components/WorkflowTaskFlow.mjs";
import { LinearProgress as LinearProgress$1 } from "../UI/loading/LinearProgress.mjs";
import { CircularProgress as CircularProgress$1 } from "../UI/loading/CircularProgress.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Card, makeStyles } from "@material-ui/core";
import { CancelIcon, ForwardIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
import { cloneDeep, orderBy } from "lodash-es";
//#region src/workflow/WorkflowUiInterruptContent.jsx
const useStyles = makeStyles((theme) => ({
	root: {},
	loadingContent: {
		flex: 1,
		display: "flex",
		flexDirection: "column",
		alignItems: "center",
		justifyContent: "center",
		height: "calc(100vh - 160px)"
	}
}));
const WorkflowUiInterruptContent = (props) => {
	const { selectedNode, workflow, reloadWorkflow, users, groups, handleClose, inquiryPageParams = {} } = props;
	const classes = useStyles();
	const [selectedPageId, setSelectedPageId] = useState("");
	const [currentWorkflowStep, setCurrentWorkflowStep] = useState(0);
	const [loading, setLoading] = useState(false);
	const [loadingTaskData, setLoadingTaskData] = useState(true);
	const [reassignSidesheetOpen, setReassignSidesheetOpen] = useState(false);
	const [reassigningAssignee, setReassigningAssignee] = useState(false);
	const [workflowPageData, setWorkflowPageData] = useState(null);
	const [orderedPageData, setOrderedPageData] = useState([]);
	const user = useUser();
	const taskDataMap = useWorkflowStore((state) => state.taskDataMap);
	const setTaskDataMap = useWorkflowStore((state_0) => state_0.setTaskDataMap);
	const { t } = useTranslation();
	const formRef = useRef(null);
	const [{ data: pageData, loading: pageLoading, error: pageError }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `page/${selectedPageId}`, {}, !!!selectedPageId, false);
	const [{ data: playScene, loading: playSceneLoading, error: playSceneError }, fetchPlayScene] = useAxiosGet(ConfigService.maestroV1ApiUrl, `maestro/play/scene/${selectedNode?.properties?.playSceneId || null}?includeData=true`, {}, !!!selectedNode?.properties?.playSceneId, false);
	const updatePlaySceneData = useCallback(async (data = "") => apiMutate(ConfigService.maestroV1ApiUrl, `maestro/play/scene/${selectedNode?.properties?.playSceneId || null}/data`, { method: "put" }, { data }), [selectedNode]);
	const updatePlaySceneState = useCallback(async (data_0 = {}, sceneState) => apiMutate(ConfigService.maestroV1ApiUrl, `maestro/play/scene/${selectedNode?.properties?.playSceneId || null}/${sceneState}`, { method: "put" }, { data: data_0 }), [selectedNode]);
	const updatePlaySceneAssignee = useCallback(async (data_1 = "") => apiMutate(ConfigService.maestroV1ApiUrl, `maestro/play/scene/${selectedNode?.properties?.playSceneId || null}/assignee`, { method: "put" }, { data: data_1 }), [selectedNode]);
	const closeReassignmentSheet = useCallback(() => {
		setReassignSidesheetOpen(false);
	}, []);
	const workflowTaskSteps = useMemo(() => {
		if (!selectedNode?.properties?.interruptPages) return [];
		return orderBy(selectedNode.properties.interruptPages, ["sequenceNo"], ["asc"]).reduce((list, ip) => {
			const step = {
				label: ip.displayName || ip.page?.name,
				pageId: ip.page?.pageId,
				requiredFieldMapping: ip.requiredFieldMapping
			};
			list.push(step);
			return list;
		}, []);
	}, [selectedNode]);
	const assigneeOptions = useMemo(() => {
		const formattedUsers = users?.reduce((list_0, user_0) => {
			list_0.push({
				id: user_0?.unityId || "",
				name: `${user_0?.displayName} - (User)` || ""
			});
			return list_0;
		}, []) || [];
		const formattedGroups = groups.reduce((list_1, group) => {
			list_1.push({
				id: group?.groupId || "",
				name: `${group?.name} - (Group)` || ""
			});
			return list_1;
		}, []) || [];
		return formattedUsers.concat(formattedGroups);
	}, [users, groups]);
	const saveCurrentWorkflowData = useCallback(async () => {
		let playSceneData = null;
		if (selectedNode?.properties?.playSceneId) playSceneData = taskDataMap[selectedNode.properties.playSceneId];
		if (playSceneData) {
			await updatePlaySceneData({ data: JSON.stringify(playSceneData) });
			await fetchPlayScene();
		}
	}, [
		taskDataMap,
		fetchPlayScene,
		updatePlaySceneData,
		selectedNode
	]);
	const updateWorkflowPageData = useCallback(async (data_2, pageId) => {
		if (!selectedNode?.properties?.playSceneId || !pageId) {
			console.warn("No TaskId or PageId availble to save Workflow Page Data");
			return;
		}
		if (selectedNode?.properties?.state === UnitStateType.Initial || selectedNode?.properties?.state === UnitStateType.Completed || selectedNode?.properties?.state === UnitStateType.Cancelled || selectedNode?.properties?.state === UnitStateType.Failed) return;
		let playSceneData_0 = null;
		if (selectedNode?.properties?.playSceneId) {
			playSceneData_0 = taskDataMap[selectedNode.properties.playSceneId];
			if (playSceneData_0) playSceneData_0[pageId] = data_2;
		}
		if (playSceneData_0) {
			await updatePlaySceneData({ data: JSON.stringify(playSceneData_0) });
			await fetchPlayScene();
		}
	}, [
		selectedNode,
		fetchPlayScene,
		taskDataMap,
		updatePlaySceneData
	]);
	const handleTaskChange = useCallback(async (step_0) => {
		setCurrentWorkflowStep(step_0);
	}, []);
	const handleTaskSubmit = useCallback(async () => {
		setLoading(true);
		await saveCurrentWorkflowData();
		await updatePlaySceneState("", 2);
		await reloadWorkflow();
		setLoading(false);
	}, [
		updatePlaySceneState,
		reloadWorkflow,
		saveCurrentWorkflowData
	]);
	const secondaryButtons = useMemo(() => {
		const buttons = [];
		if (handleClose) buttons.push({
			label: t("Close"),
			component: CancelIcon,
			click: () => handleClose()
		});
		if (selectedNode?.properties?.state !== UnitStateType.Started) return buttons;
		buttons.push({
			label: t("Reassign"),
			component: ForwardIcon,
			click: () => setReassignSidesheetOpen(true)
		});
		return buttons;
	}, [
		t,
		selectedNode,
		handleClose
	]);
	const handleReassignment = useCallback(() => {
		formRef?.current.form.submit();
	}, []);
	const reassignTask = useCallback(async (values) => {
		setReassigningAssignee(true);
		await updatePlaySceneAssignee({ data: values?.assignee?.id || "" });
		await fetchPlayScene();
		setReassigningAssignee(false);
		closeReassignmentSheet();
	}, [
		updatePlaySceneAssignee,
		fetchPlayScene,
		closeReassignmentSheet
	]);
	const requiredFieldMapping = useMemo(() => {
		const step_1 = workflowTaskSteps?.find((wts) => wts.pageId === pageData?.pageId);
		let fieldMapping = step_1?.requiredFieldMapping ? cloneDeep(step_1.requiredFieldMapping) : {};
		const workflowVariables = selectedNode?.properties?.variables || null;
		if (!!fieldMapping && !!workflowVariables) Object.keys(fieldMapping)?.forEach((rfmKey) => {
			const requiredField = fieldMapping[rfmKey];
			if (!!requiredField?.value) {
				if (requiredField?.type === "workflowVariable") {
					let matchedVariable = false;
					Object.keys(workflowVariables).forEach((key) => {
						if (requiredField.value === key) {
							requiredField.value = workflowVariables[key] || "";
							matchedVariable = true;
							return;
						}
					});
					if (!matchedVariable) requiredField.value = null;
				}
			}
		});
		return fieldMapping || {};
	}, [
		pageData?.pageId,
		selectedNode,
		workflowTaskSteps
	]);
	const pageWidgetParams = useMemo(() => {
		const requiredFieldsMap = Object.keys(requiredFieldMapping).reduce((fieldMap, key_0) => {
			fieldMap[key_0] = requiredFieldMapping[key_0]?.value || "";
			return fieldMap;
		}, {});
		return {
			setSideSheetWidth: () => {
				console.warn("setSideSheetWidth Not implemented");
			},
			setSideSheetButtonLabel: () => {
				console.warn("setSideSheetButtonLabel Not implemented");
			},
			setSideSheetOnSubmit: () => {
				console.warn("setSideSheetOnSubmit Not implemented");
			},
			setSideSheetAdditionalOnClose: () => {
				console.warn("setSideSheetAdditionalOnClose Not implemented");
			},
			setSideSheetProps: () => {
				console.warn("setSideSheetProps Not implemented");
			},
			closeSideSheet: () => {
				console.warn("closeSideSheet Not implemented");
			},
			onCreate: () => {
				console.warn("onCreate Not implemented");
			},
			onUpdate: () => {
				console.warn("onUpdate Not implemented");
			},
			...inquiryPageParams,
			pageId: pageData?.pageId,
			updateWorkflowPageData: (data_3) => updateWorkflowPageData(data_3, pageData?.pageId),
			workflowTask: selectedNode,
			workflowPageData: {
				...requiredFieldsMap,
				...workflowPageData
			},
			requiredFieldsMap: requiredFieldMapping || null,
			currentWorkflowStep,
			orderedWorkflowPageData: orderedPageData
		};
	}, [
		pageData?.pageId,
		selectedNode,
		workflowPageData,
		updateWorkflowPageData,
		requiredFieldMapping,
		inquiryPageParams,
		currentWorkflowStep,
		orderedPageData
	]);
	const currentAssignee = useMemo(() => {
		if (!playScene?.assignee || !assigneeOptions?.length) return "";
		return assigneeOptions.find((assignee) => assignee.id === playScene.assignee) || "";
	}, [playScene, assigneeOptions]);
	const pageHeight = useMemo(() => "calc(100vh - 162px)", []);
	useEffect(() => {
		if (!selectedNode?.properties?.playSceneId || !selectedPageId || loadingTaskData) {
			setWorkflowPageData(null);
			return;
		}
		if (taskDataMap?.[selectedNode.properties.playSceneId] && taskDataMap[selectedNode.properties.playSceneId][selectedPageId]) {
			setWorkflowPageData(taskDataMap[selectedNode.properties.playSceneId][selectedPageId]);
			return;
		}
		if (Object.keys(taskDataMap).length && selectedNode?.properties?.playSceneId && selectedPageId && !playSceneLoading && !loadingTaskData) {
			setWorkflowPageData((prevData) => {
				if (!prevData) return {};
				else if (!Object.keys(prevData).length) return prevData;
			});
			return;
		}
		setWorkflowPageData(null);
	}, [
		selectedNode,
		selectedPageId,
		taskDataMap,
		loadingTaskData,
		playSceneLoading,
		workflowTaskSteps
	]);
	useEffect(() => {
		if (workflowTaskSteps?.length) setSelectedPageId(workflowTaskSteps[currentWorkflowStep]?.pageId);
	}, [workflowTaskSteps, currentWorkflowStep]);
	useEffect(() => {
		setLoadingTaskData(true);
		if (!playSceneLoading && selectedNode?.properties?.playSceneId) {
			const json = playScene?.data ? JSON.parse(playScene.data) : {};
			setTaskDataMap(selectedNode.properties.playSceneId, json);
		}
		setLoadingTaskData(false);
	}, [
		playScene,
		playSceneLoading,
		setTaskDataMap,
		selectedNode
	]);
	useEffect(() => {
		const orderedData = [];
		if (taskDataMap?.[selectedNode.properties.playSceneId]) workflowTaskSteps.forEach((step_2) => {
			orderedData.push(taskDataMap[selectedNode.properties.playSceneId][step_2.pageId] || {});
		});
		setOrderedPageData(orderedData);
	}, [
		taskDataMap,
		workflowTaskSteps,
		selectedNode
	]);
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Card, {
		variant: "outlined",
		style: {
			border: "none",
			paddingBottom: workflowTaskSteps?.length > 1 ? 10 : 0
		}
	}, /* @__PURE__ */ React.createElement(PrimaryActionHeader, {
		single: true,
		title: workflow?.name,
		buttonLabel: "Submit",
		handleClick: handleTaskSubmit,
		pabDisabled: selectedNode?.properties?.state !== UnitStateType.Started,
		secondaryButtons
	}), loading && /* @__PURE__ */ React.createElement(LinearProgress$1, null)), workflowTaskSteps?.length > 1 && /* @__PURE__ */ React.createElement(WorkflowTaskFlow, {
		steps: workflowTaskSteps,
		handleClick: handleTaskChange,
		task: selectedNode
	}), selectedPageId && workflowPageData ? /* @__PURE__ */ React.createElement(PageContainer, {
		user,
		key: selectedPageId,
		pageData,
		pageLoading,
		widgetParams: pageWidgetParams,
		disableMargins: true,
		fromMenu: true,
		height: pageHeight
	}) : /* @__PURE__ */ React.createElement("div", { className: classes.loadingContent }, /* @__PURE__ */ React.createElement(CircularProgress$1, { size: 64 })), /* @__PURE__ */ React.createElement(SideSheet, {
		open: reassignSidesheetOpen,
		buttonLabel: t("Reassign"),
		onClose: closeReassignmentSheet,
		onSubmit: handleReassignment,
		title: t("Reassign Task"),
		width: "25%",
		progress: reassigningAssignee,
		variant: "indeterminate"
	}, /* @__PURE__ */ React.createElement(Form, {
		onSubmit: reassignTask,
		ref: formRef
	}, /* @__PURE__ */ React.createElement(Field, {
		component: FluentTextFieldAutoComplete,
		name: "assignee",
		id: "assignee",
		label: t("Assignee"),
		initialValue: currentAssignee || "",
		options: assigneeOptions || [],
		optionKey: "name",
		variant: "outlined",
		margin: "dense"
	}))));
};
//#endregion
export { WorkflowUiInterruptContent };

//# sourceMappingURL=WorkflowUiInterruptContent.mjs.map