import { findTermByType } from "../utilities/maintenanceEngine/CrudBrowserUtilities.mjs";
import { LogicalSearchOperatorEnums, LookupTypeIdEnums, UdpEnums } from "../enums/unitySystemEnums.mjs";
import { toTitleCase, toUpperFirstChar } from "../utilities/input/StringUtilities.mjs";
import { getSanitizedName } from "../utilities/entities/entityUtilities.mjs";
import { SqlFilterOperators } from "../enums/aggridEnums.mjs";
import { getSearchObject } from "../utilities/search/SearchUtilities.mjs";
import { SideSheet } from "../UI/surfaces/SideSheet.mjs";
import { useLookupsStore } from "../stores/lookupsStore.mjs";
import { usePromotedMethodEntity } from "../hooks/usePromotedMethodEntity.mjs";
import { executeQueryAdHoc, executeQueryWithParameters } from "../udp/utilities/methodUtils.mjs";
import { useAgGridApi } from "../utilities/aggrid/AgTable.mjs";
import { FluentDialog } from "../UI/feedback/FluentDialog.mjs";
import { useQueryExecutors } from "../hooks/useQueryExecutors.mjs";
import { SearchMethodUdpGrid } from "../UI/templates/newGrid/SearchMethodUdpGrid.mjs";
import { CrudTableSidePanel } from "../maintenanceEngine/crudBrowser/CrudTableSidePanel.mjs";
import { ClientSideUdpGrid } from "../UI/templates/newGrid/ClientSideUdpGrid.mjs";
import { DataBrowserColumnDefs } from "./DataBrowserColumnDefs.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useHistory } from "react-router-dom";
import { DateTime } from "luxon";
import { useTranslation } from "react-i18next";
import { cloneDeep } from "lodash-es";
//#region src/dataBrowser/DataBrowserContainer.jsx
const GRID_ID = "4be3be45-1930-4ab9-b7b7-0c0fa3e30490";
const DataBrowserContainer = (props) => {
	const { entityData, onCreate, onUpdate, onDelete, onLoadInquiryNode, entityAttributes, foreignKeyData, loading, promotedEntity, isServerSide = false, setGridApi, filterElements, backToConfigPage, queryColumnsData, lookupsMap = {}, ...other } = props;
	const [dialogOpen, setDialogOpen] = useState(false);
	const [sideSheetOpenState, setSideSheetOpenState] = useState({
		add: false,
		update: false
	});
	const [sideSheetWidth, setSideSheetWidth] = useState(600);
	const [, setSideSheetButtonLabel] = useState("");
	const [, setOtherSideSheetProps] = useState({});
	const [, setSideSheetOnSubmit] = useState(() => () => console.warn("onSubmit not set"));
	const [, setFilterChipsArray] = useState([]);
	const [searchFilterElements, setSearchFilterElements] = useState(filterElements);
	const [entityUdpObjectInfo, setEntityUdpObjectInfo] = useState(null);
	const { t } = useTranslation();
	const history = useHistory();
	const { gridApi } = useAgGridApi();
	const { getCleanData } = useQueryExecutors();
	const lookupApiMethodId = useLookupsStore((state) => state.lookupApiMethodId);
	const [selectedEntity, setSelectedEntity] = useState(null);
	const gridApiRef = useRef(null);
	const handleSideSheet = useCallback((type, open, selectedEntity_0) => {
		setSelectedEntity(selectedEntity_0);
		setSideSheetOpenState((prev) => ({
			...prev,
			[type]: open
		}));
	}, []);
	const { data: udpObjectInfoEntity } = usePromotedMethodEntity("udpObjectInfo", true);
	const entityName = useMemo(() => {
		if (!promotedEntity) return "";
		return promotedEntity.entityName || "";
	}, [promotedEntity]);
	const commonEntityName = useMemo(() => {
		if (!entityName && !entityUdpObjectInfo) return "";
		return toTitleCase(entityUdpObjectInfo?.properties?.displayName || getSanitizedName(entityName));
	}, [entityName, entityUdpObjectInfo]);
	const createApiMethodPageId = useMemo(() => {
		return promotedEntity?.unityBaseCreateMethod?.pageId;
	}, [promotedEntity]);
	const secondaryActionButtons = useMemo(() => {
		const actions = [];
		if (backToConfigPage) actions.push({
			onClick: backToConfigPage,
			label: t("Back To Config"),
			iconName: "settings",
			tooltip: t("Back To Config"),
			background: "transparent"
		});
		return actions;
	}, [backToConfigPage, t]);
	const closeDialog = useCallback(() => {
		setDialogOpen(false);
	}, []);
	const deleteDialogConfig = useMemo(() => {
		return {
			title: t("Delete"),
			message: t("Are you sure you want to delete this row?"),
			actionOne: closeDialog,
			labelOne: t("Cancel"),
			actionTwo: onDelete,
			labelTwo: t("Confirm"),
			loading: !!!foreignKeyData
		};
	}, [
		closeDialog,
		foreignKeyData,
		onDelete,
		t
	]);
	const actionList = useMemo(() => {
		if (!promotedEntity) return;
		const actions_0 = [{
			id: 1,
			title: promotedEntity?.unityBaseUpdateMethod ? t("Edit") : t("Edit Method Not Accessible"),
			iconName: "edit",
			handleOnClick: (e, params) => handleSideSheet("update", true, params?.data),
			disabled: !!!promotedEntity?.unityBaseUpdateMethod
		}, {
			id: 2,
			title: promotedEntity?.unityBaseDeleteMethod ? t("Delete") : t("Delete Method Not Accessible"),
			iconName: "trashCan",
			handleOnClick: () => setDialogOpen(true),
			opens: "dialog",
			disabled: !!!promotedEntity?.unityBaseDeleteMethod
		}];
		if (!!onLoadInquiryNode) actions_0.push({
			id: 5,
			title: t("Load to Tree"),
			iconName: "migrateAlt",
			handleOnClick: (e_0, params_0) => {
				onLoadInquiryNode(getCleanData(params_0?.data, lookupsMap));
			},
			loading: !!!foreignKeyData,
			view: {}
		});
		return actions_0;
	}, [
		promotedEntity,
		t,
		onLoadInquiryNode,
		handleSideSheet,
		foreignKeyData,
		getCleanData,
		lookupsMap
	]);
	const virtualActions = useMemo(() => {
		return [{
			id: 3,
			title: t("Open Virtual Table"),
			iconName: "search",
			loading: !!!foreignKeyData,
			handleOnClick: (value) => {
				history.push({
					pathname: `/virtual/${value.id}`,
					search: `?entityName=${entityName}`,
					state: {
						value,
						promotedEntity,
						label: value.name
					}
				});
			},
			checkDisabled: (value_0) => value_0.typeId !== LookupTypeIdEnums.Lookup
		}];
	}, [
		entityName,
		t,
		history,
		promotedEntity,
		foreignKeyData
	]);
	const jointActionList = useMemo(() => {
		if (!actionList) return [];
		if (entityName.toLowerCase() === UdpEnums.Udp_Lookup.toLowerCase()) return [...actionList, ...virtualActions];
		return actionList;
	}, [
		actionList,
		virtualActions,
		entityName
	]);
	const columnDefs = useMemo(() => {
		return DataBrowserColumnDefs(entityAttributes, jointActionList, true, queryColumnsData);
	}, [
		entityAttributes,
		jointActionList,
		queryColumnsData
	]);
	const sideSheetList = useMemo(() => {
		const data = getCleanData(entityData, lookupsMap);
		return [{
			open: sideSheetOpenState.add,
			closeSheet: () => handleSideSheet("add", false),
			title: `Add New ${commonEntityName}`,
			width: sideSheetWidth,
			children: /* @__PURE__ */ React.createElement(CrudTableSidePanel, {
				entityAttributes,
				foreignKeyData,
				onCreate,
				closeSideSheet: () => handleSideSheet("add", false),
				pageId: createApiMethodPageId,
				setSideSheetWidth,
				setSideSheetButtonLabel,
				setSideSheetOnSubmit,
				setSideSheetProps: setOtherSideSheetProps,
				isNewEntry: true,
				entityData,
				entityName
			})
		}, {
			open: sideSheetOpenState.update,
			closeSheet: () => handleSideSheet("update", false),
			title: `Update ${commonEntityName}`,
			width: 550,
			children: /* @__PURE__ */ React.createElement(CrudTableSidePanel, {
				entityAttributes,
				foreignKeyData,
				crudTableEditionData: selectedEntity,
				onUpdate,
				closeSideSheet: () => handleSideSheet("update", false),
				closeSideSheetPropName: "closeSideSheet",
				pageId: promotedEntity?.unityBaseUpdateMethod?.pageId,
				isNewEntry: false,
				entityData: data,
				entityName
			})
		}];
	}, [
		commonEntityName,
		createApiMethodPageId,
		entityAttributes,
		entityData,
		entityName,
		foreignKeyData,
		handleSideSheet,
		onCreate,
		onUpdate,
		promotedEntity,
		selectedEntity,
		sideSheetOpenState,
		sideSheetWidth,
		getCleanData,
		lookupsMap
	]);
	const SideOptionList = useMemo(() => {
		return sideSheetList.map((item, index) => /* @__PURE__ */ React.createElement(SideSheet, {
			open: item.open,
			onClose: item.closeSheet,
			title: item.title,
			width: item.width,
			key: index
		}, item.children));
	}, [sideSheetList]);
	const getLookupResults = useCallback(async () => {
		if (!lookupsMap || !lookupApiMethodId) return null;
		const lookupId = Object.values(lookupsMap).find((item_0) => item_0.filterOn)?.value || "";
		if (lookupId) return await executeQueryWithParameters({ data: { id: lookupId } }, lookupApiMethodId);
		return null;
	}, [lookupsMap, lookupApiMethodId]);
	const formattedData = useMemo(() => {
		if (entityData) {
			let formattedEntityData = cloneDeep(entityData);
			const datetimeFields = entityAttributes?.reduce((defs, element) => {
				if (!element?.extendedProperties?.childEntity && findTermByType(element?.type, "datetime")) defs.push(element?.name.charAt(0).toLowerCase() + element?.name.slice(1));
				return defs;
			}, []);
			if (datetimeFields?.length) formattedEntityData.forEach((e_1) => {
				Object.keys(e_1).forEach((key) => {
					if (datetimeFields.find((field) => field === key)) {
						if (e_1[key] === null) return;
						e_1[key] = DateTime.fromJSDate(new Date(e_1[key])).toFormat("yyyy/MM/dd HH:mm:ss");
					}
				});
			});
			return formattedEntityData;
		}
		return [];
	}, [entityAttributes, entityData]);
	const handleChipToggle = useCallback((chip) => {
		if (isServerSide && chip && chip.filterValue && chip.keyName) {
			const updatedSearchFilterElements = [...searchFilterElements];
			const chipFilterElement = {
				searchValue: chip.filterValue,
				searchField: toUpperFirstChar(chip.keyName),
				searchOperator: SqlFilterOperators.EQUALS
			};
			updatedSearchFilterElements.push(chipFilterElement);
			setSearchFilterElements(updatedSearchFilterElements);
		}
	}, [isServerSide, searchFilterElements]);
	const handleChipUntoggle = useCallback(() => {
		setSearchFilterElements(filterElements);
	}, [filterElements]);
	const setFilterChips = useCallback(async () => {
		let filterChipsArray = [];
		const lookupResults = (await getLookupResults())?.data;
		if (!lookupResults) {
			setFilterChipsArray([]);
			return;
		}
		let keyName = lookupResults.keyName;
		const valueName = lookupResults.valueName;
		const lookupToFilterOn_0 = Object.values(lookupsMap).find((item_1) => item_1.filterOn);
		let chipKey = keyName;
		const lookupMapKeys = Object.keys(lookupsMap);
		for (let i = 0; i < lookupMapKeys.length; i++) {
			const key_0 = lookupMapKeys[i];
			if (lookupsMap[key_0].value === lookupToFilterOn_0?.value) {
				chipKey = key_0;
				break;
			}
		}
		for (let i_0 = 0; i_0 < lookupResults?.data.length; i_0++) {
			const lookupResult_0 = lookupResults.data[i_0];
			const label = lookupResult_0[valueName];
			const numRows = formattedData?.filter((obj_0) => obj_0[keyName] === label)?.length;
			let chipData = {
				label: `${label}`,
				value: !isServerSide ? numRows || "" : "",
				filterValue: lookupResult_0[keyName],
				id: i_0,
				keyName: chipKey
			};
			chipData.onToggle = () => handleChipToggle(chipData);
			chipData.onUntoggle = () => handleChipUntoggle();
			if (!isServerSide && numRows > 0) filterChipsArray.push(chipData);
			if (isServerSide) filterChipsArray.push(chipData);
		}
		setFilterChipsArray(filterChipsArray);
	}, [
		getLookupResults,
		handleChipToggle,
		handleChipUntoggle,
		isServerSide,
		formattedData,
		lookupsMap
	]);
	useEffect(() => {
		setFilterChips();
	}, [setFilterChips]);
	useEffect(() => {
		setSearchFilterElements(filterElements || []);
	}, [filterElements]);
	useEffect(() => {
		if (!gridApi) return;
		if (setGridApi) setGridApi(gridApi);
	}, [gridApi, setGridApi]);
	useEffect(() => {
		const executeSearchForEntityUdpObjectInfo = async (apiMethodId, sanitizedEntityName) => {
			const response = await executeQueryAdHoc({ data: getSearchObject([{
				searchField: "SanitizedName",
				searchOperator: "=",
				searchValue: sanitizedEntityName
			}], 1, 50, false) }, apiMethodId);
			if (response.status === 200) {
				const data_0 = response?.data?.pageList[0];
				setEntityUdpObjectInfo(data_0);
			}
		};
		if (udpObjectInfoEntity?.unityBaseSearchMethod && entityName) executeSearchForEntityUdpObjectInfo(udpObjectInfoEntity?.unityBaseSearchMethod?.apiMethodId, getSanitizedName(entityName));
	}, [udpObjectInfoEntity, entityName]);
	const handleGridApiCallback = (api) => {
		gridApiRef.current = api;
	};
	const gridHeaderConfig = useMemo(() => {
		return {
			title: commonEntityName,
			primaryActionButton: {
				label: t("Add"),
				iconName: "add",
				onClick: () => handleSideSheet("add", true, null)
			},
			secondaryActionButtons
		};
	}, [
		commonEntityName,
		handleSideSheet,
		secondaryActionButtons,
		t
	]);
	const gridFunctions = useMemo(() => {
		return [
			{ name: "agGridExport" },
			{ name: "agGridHideShowColumns" },
			{ name: "agGridSizeColumnsToFit" },
			{ name: "agGridAutoSizeColumns" },
			{ name: "openSavedViews" },
			{ name: "quickFilter" }
		];
	}, []);
	const gridOptions = useMemo(() => {
		return {
			pagination: true,
			paginationPageSize: 20
		};
	}, []);
	const searchMethodConfig = useMemo(() => {
		const searchObject = getSearchObject(searchFilterElements, 1, null, false, LogicalSearchOperatorEnums.And);
		return {
			apiMethodId: promotedEntity?.unityBaseSearchMethod?.apiMethodId,
			customSearchObject: searchObject
		};
	}, [promotedEntity, searchFilterElements]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, isServerSide && !!promotedEntity ? /* @__PURE__ */ React.createElement(SearchMethodUdpGrid, {
		gridId: GRID_ID,
		searchMethodConfig,
		columnDefs,
		gridApiCallback: handleGridApiCallback,
		gridHeaderConfig,
		gridFunctions: [{ name: "agGridRefreshData" }, ...gridFunctions],
		gridOptions,
		loading,
		...other
	}) : /* @__PURE__ */ React.createElement(ClientSideUdpGrid, {
		gridId: GRID_ID,
		rowData: formattedData,
		columnDefs,
		gridApiCallback: handleGridApiCallback,
		gridHeaderConfig,
		gridFunctions,
		gridOptions,
		loading,
		...other
	}), SideOptionList, /* @__PURE__ */ React.createElement(FluentDialog, {
		open: dialogOpen,
		handleClose: closeDialog,
		title: deleteDialogConfig?.title,
		message: deleteDialogConfig?.message,
		actionOne: deleteDialogConfig?.actionOne,
		labelOne: deleteDialogConfig?.labelOne,
		actionTwo: deleteDialogConfig?.actionTwo,
		labelTwo: deleteDialogConfig?.labelTwo,
		progress: deleteDialogConfig?.loading
	}));
};
//#endregion
export { DataBrowserContainer };

//# sourceMappingURL=DataBrowserContainer.mjs.map