import { ConfigService } from "../../configService/index.mjs";
import { NodeActionEnums } from "../../enums/unitySystemEnums.mjs";
import { apiMutate } from "../useAxiosMutate.mjs";
import { ActionDispatchContext } from "../../contexts/ActionDispatchContext.mjs";
import { ActionContext } from "../../contexts/ActionContext.mjs";
import { useActionStore } from "../../stores/actionStore.mjs";
import { ActionLoadingDispatchContext } from "../../contexts/ActionLoadingDispatchContext.mjs";
import { useCatalogStore } from "../../stores/catalogStore.mjs";
import { useShellStore } from "../../stores/shellStore.mjs";
import { useAxiosGet } from "../useAxiosGet.mjs";
import { ActionWrapper } from "../../actions/ActionWrapper.mjs";
import { usePromotedLookupMethods } from "../../hooks/usePromotedLookupMethods.mjs";
import LoadingOverlay from "../../UI/loading/LoadingOverlay.mjs";
import { useAuthedUser } from "../auth/useAuthedUser.mjs";
import useDefaultFormValues from "../crud/useDefaultFormValues.mjs";
import { ActionLoadingContext } from "../../contexts/ActionLoadingContext.mjs";
import { usePromotedMethodEntities } from "../../hooks/usePromotedMethodEntities.mjs";
import React, { useCallback, useEffect, useMemo, useReducer, useState } from "react";
import { useHistory } from "react-router-dom";
import { createPortal } from "react-dom";
//#region src/utilities/provider/ActionProvider.jsx
const emptyAction = {
	action: {
		actionId: "",
		payload: null
	},
	actionPanels: {},
	catalog: null,
	catalogPromise: null,
	catalogEntities: [],
	catalogPromotedEntities: [],
	menuListState: {
		menuList: [],
		handleRemoveMenuItem: () => {},
		selectedMenuIndex: null
	},
	modal: {
		open: false,
		action: null,
		title: ""
	},
	inquiryParams: { 0: {
		selectedNode: null,
		selectedNodeParent: null,
		refreshTree: null
	} },
	showInquiryHeaderActions: true,
	sideSheet: {
		open: false,
		action: null
	},
	splitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	},
	pageSplitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	},
	pageContainerSplitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	},
	setCurrentEntityName: null
};
const newRouteEmptyAction = {
	action: {
		actionId: "",
		payload: null
	},
	actionPanels: {},
	menuListState: {
		menuList: [],
		handleRemoveMenuItem: () => {},
		selectedMenuIndex: null
	},
	modal: {
		open: false,
		action: null,
		title: ""
	},
	selectedNodeObj: null,
	inquiryParams: { 0: {
		selectedNode: null,
		selectedNodeParent: null,
		refreshTree: null
	} },
	showInquiryHeaderActions: true,
	sideSheet: {
		open: false,
		action: null
	},
	splitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	},
	pageSplitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	},
	pageContainerSplitScreen: {
		open: false,
		action: null,
		type: null,
		params: null
	}
};
const emptyActionLoading = {
	loading: false,
	waitingToExecute: ""
};
const ActionProvider = (props) => {
	const { domRoot, children } = props;
	const user = useAuthedUser();
	const history = useHistory();
	const [apiCatalogId, setApiCatalogId] = useState(null);
	const [foreignKeyData, setForeignKeyData] = useState([]);
	const [actionPanel, setActionPanel] = useState(null);
	const [currentEntityName, setCurrentEntityName] = useState(null);
	const [currentLocationPathname, setCurrentLocationPathname] = useState(history?.location?.pathname);
	usePromotedMethodEntities(apiCatalogId);
	const selectedNode = useActionStore((state) => state.selectedNode);
	const currentContainerId = useShellStore((state_0) => state_0.currentContainerId);
	usePromotedLookupMethods(apiCatalogId);
	const setCurrentApiCatalogId = useCatalogStore((state_1) => state_1.setCurrentApiCatalogId);
	const [{ data: tpacb, loading: tpacbLoading }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `tenantProductApiCatalogBase/tenant/${user?.currentTenantId}/product/${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !user?.currentTenantId, false);
	const [actionState, dispatch] = useReducer((state_2, reducerAction) => {
		switch (reducerAction.type) {
			case "SET_ACTION_PANELS":
				let containerIdToUse = 0;
				if (reducerAction.containerId) containerIdToUse = reducerAction.containerId;
				const updatedActionPanels = { ...state_2.actionPanels };
				updatedActionPanels[containerIdToUse] = reducerAction.actionPanels;
				state_2 = {
					...state_2,
					actionPanels: updatedActionPanels
				};
				break;
			case "OPEN_SIDESHEET":
				state_2 = {
					...state_2,
					sideSheet: reducerAction.sideSheet
				};
				break;
			case "OPEN_MODAL":
				state_2 = {
					...state_2,
					modal: reducerAction.modal
				};
				break;
			case "CLOSE_ALL_SPLIT_SCREENS":
				state_2 = {
					...state_2,
					splitScreen: {
						open: false,
						action: null,
						type: null,
						params: null
					},
					pageSplitScreen: {
						open: false,
						action: null,
						type: null,
						params: null
					},
					pageContainerSplitScreen: {
						open: false,
						action: null,
						type: null,
						params: null
					}
				};
				break;
			case "OPEN_SPLIT_SCREEN":
				state_2 = {
					...state_2,
					splitScreen: reducerAction.splitScreen
				};
				break;
			case "OPEN_PAGE_SPLIT_SCREEN":
				state_2 = {
					...state_2,
					pageSplitScreen: reducerAction.pageSplitScreen
				};
				break;
			case "OPEN_PAGE_CONTAINER_SPLIT_SCREEN":
				state_2 = {
					...state_2,
					pageContainerSplitScreen: reducerAction.pageContainerSplitScreen
				};
				break;
			case "SET_CATALOG_ENTITIES":
				state_2 = {
					...state_2,
					catalogEntities: reducerAction.catalogEntities
				};
				break;
			case "SET_CATALOG_PROMOTED_ENTITIES":
				state_2 = {
					...state_2,
					catalogPromotedEntities: reducerAction.catalogPromotedEntities
				};
				break;
			case "SET_INQUIRY_PARAMS":
				let initialContainerId = 0;
				if (reducerAction.containerId) initialContainerId = reducerAction.containerId;
				const updatedInquiryParams = { ...state_2.inquiryParams };
				updatedInquiryParams[initialContainerId] = reducerAction.inquiryParams;
				state_2 = {
					...state_2,
					inquiryParams: updatedInquiryParams
				};
				break;
			case "SET_SHOW_INQUIRY_HEADER_ACTIONS":
				state_2 = {
					...state_2,
					showInquiryHeaderActions: reducerAction.showInquiryHeaderActions
				};
				break;
			case "SET_MENU_LIST_STATE":
				state_2 = {
					...state_2,
					menuListState: reducerAction.menuListState
				};
				break;
			case "SET_ACTION_STATE_FOR_NEW_ROUTE":
				state_2 = {
					...state_2,
					...newRouteEmptyAction
				};
				break;
			default: throw new Error(`Unknown action type ${reducerAction.type}`);
		}
		state_2 = {
			...state_2,
			setCurrentEntityName
		};
		return state_2;
	}, emptyAction);
	const [actionLoadingState, dispatchActionLoading] = useReducer((state_3, reducerAction_0) => {
		switch (reducerAction_0.type) {
			case "SET_ACTION_LOADING":
				state_3 = {
					...state_3,
					loading: reducerAction_0.loading
				};
				break;
			case "SET_ACTION_WAITING_TO_EXECUTE":
				state_3 = {
					...state_3,
					waitingToExecute: reducerAction_0.actionId
				};
				break;
			default: throw new Error(`Unknown action loading type ${reducerAction_0.type}`);
		}
		return state_3;
	}, emptyActionLoading);
	const action = useMemo(() => {
		let selectedAction = null;
		if (actionState) {
			if (actionState.modal?.action) selectedAction = actionState.modal.action;
			if (actionState.sideSheet?.action) selectedAction = actionState.sideSheet.action;
			if (actionState.splitScreen?.action) selectedAction = actionState.splitScreen.action;
			if (actionState.pageSplitScreen?.action) selectedAction = actionState.pageSplitScreen.action;
			if (actionState.pageContainerSplitScreen?.action) selectedAction = actionState.pageContainerSplitScreen.action;
		}
		return selectedAction;
	}, [actionState]);
	const entityName = useMemo(() => {
		return actionPanel ? actionPanel.entityName : currentEntityName;
	}, [actionPanel, currentEntityName]);
	const [{ data: catalogObject }] = useAxiosGet(ConfigService.integrationV2ApiUrl, `apiCatalog/${apiCatalogId}/catalogObject/${entityName}`, {}, !!!apiCatalogId || !!!entityName, false);
	const entityAttributes = useMemo(() => {
		return catalogObject?.properties ?? [];
	}, [catalogObject]);
	const { defaultFormValues } = useDefaultFormValues(entityAttributes);
	const [crudTableFormData, setCrudTableFormData] = useState(defaultFormValues);
	const crudTableEditionData = useMemo(() => {
		let crudData = null;
		if (selectedNode?.nodeObj && action && action.actionTypeId === NodeActionEnums.Update) {
			crudData = selectedNode.nodeObj;
			setCrudTableFormData(selectedNode.nodeObj);
		} else setCrudTableFormData(defaultFormValues);
		return crudData;
	}, [action, selectedNode]);
	const executeAction = useCallback(async (data, id) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${id}`, { method: "post" }, data), []);
	const inquiryActions = /* @__PURE__ */ React.createElement(ActionWrapper, {
		action,
		actionState,
		actionPanel,
		dispatch,
		apiCatalogId,
		executeAction,
		splitScreenBody: children,
		entityAttributes,
		foreignKeyData,
		setForeignKeyData,
		crudTableEditionData,
		crudTableFormData
	});
	useEffect(() => {
		if (tpacb) {
			setApiCatalogId(tpacb.apiCatalogId);
			setCurrentApiCatalogId(tpacb.apiCatalogId);
		}
	}, [tpacb, setCurrentApiCatalogId]);
	useEffect(() => {
		if (action && actionState) setActionPanel(actionState?.actionPanels[currentContainerId || 0]?.find((ap) => ap.panelActions.find((pa) => pa.actionId === action.actionId)));
	}, [
		action,
		actionState,
		currentContainerId
	]);
	useEffect(() => dispatchActionLoading({
		type: "SET_ACTION_LOADING",
		loading: tpacbLoading
	}), [tpacbLoading]);
	useEffect(() => {
		if (history) return history.listen((location) => {
			if (currentLocationPathname !== location.pathname) {
				setCurrentLocationPathname(location.pathname);
				dispatch({ type: "SET_ACTION_STATE_FOR_NEW_ROUTE" });
			}
		});
	}, [history, currentLocationPathname]);
	const actionLoading = useMemo(() => /* @__PURE__ */ React.createElement(LoadingOverlay, { open: !!actionLoadingState.waitingToExecute }), [actionLoadingState]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, actionLoading, /* @__PURE__ */ React.createElement(ActionContext.Provider, { value: actionState }, /* @__PURE__ */ React.createElement(ActionDispatchContext.Provider, { value: dispatch }, /* @__PURE__ */ React.createElement(ActionLoadingContext.Provider, { value: actionLoadingState }, /* @__PURE__ */ React.createElement(ActionLoadingDispatchContext.Provider, { value: dispatchActionLoading }, domRoot ? createPortal(inquiryActions, domRoot) : inquiryActions)))));
};
//#endregion
export { ActionProvider };

//# sourceMappingURL=ActionProvider.mjs.map