import { ConfigService } from "../../../configService/index.mjs";
import { UdpPageEnums } from "../../../enums/pageEnums.mjs";
import { useUser } from "../../../utilities/auth/useUser.mjs";
import { apiMutate } from "../../../utilities/useAxiosMutate.mjs";
import { SqlFilterOperators } from "../../../enums/aggridEnums.mjs";
import { parseSearchParamsIntoFilterObjects } from "../../../utilities/search/SearchUtilities.mjs";
import { SideSheet } from "../../../UI/surfaces/SideSheet.mjs";
import { PageLoading } from "../../../UI/feedback/PageLoading.mjs";
import { useTenant } from "../../../utilities/tenant/useTenant.mjs";
import { SearchMethodUdpGrid } from "../../../UI/templates/newGrid/SearchMethodUdpGrid.mjs";
import CustomMenuPage from "../../../menuPage/CustomMenuPage.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { FormControlLabel, Switch, TextField } from "@material-ui/core";
import { useSnackbar } from "notistack";
import { useHistory, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Autocomplete } from "@material-ui/lab";
//#region src/udp/pages/UdpFormsSubmissionGrid/UdpFormsSubmissionGrid.jsx
const UdpFormsSubmissionGridIds = Object.freeze({
	ResponderId: "5C4A93B6-6C25-4236-ABCA-2E23DC6540B5",
	ManagerId: "15F165D1-82CD-4775-9A35-FF2153058240"
});
const UdpFormsSubmissionStatusEnum = Object.freeze({
	InProgress: 1,
	Submitted: 2,
	Created: 3
});
const formatDateTime = (dateString) => {
	let normalizedDateString = dateString;
	if (dateString.includes(" ")) normalizedDateString = dateString.replace(" ", "T");
	if (!dateString.toUpperCase().endsWith("Z")) normalizedDateString = normalizedDateString + "Z";
	return new Date(normalizedDateString).toLocaleString(void 0, {
		year: "numeric",
		month: "short",
		day: "numeric",
		hour: "2-digit",
		minute: "2-digit",
		hour12: true
	});
};
const toUtcIsoAtLocalEndOfDay = (yyyyMmDd) => {
	if (!yyyyMmDd) return null;
	const [y, m, d] = String(yyyyMmDd).split("-").map((x) => Number(x));
	if (!y || !m || !d) return null;
	return new Date(y, m - 1, d, 23, 59, 59, 0).toISOString();
};
const tryParseJsonObject = (value) => {
	if (!value) return null;
	if (typeof value === "object") return value;
	if (typeof value !== "string") return null;
	try {
		return JSON.parse(value);
	} catch {
		return null;
	}
};
const hasNonWhitespaceText = (v) => typeof v === "string" && v.trim().length > 0;
const formatDateForFilename = (dateString) => {
	if (!dateString) return "";
	let normalizedDateString = dateString;
	if (typeof normalizedDateString === "string" && normalizedDateString.includes(" ")) normalizedDateString = normalizedDateString.replace(" ", "T");
	if (typeof normalizedDateString === "string" && !normalizedDateString.toUpperCase().endsWith("Z")) normalizedDateString = normalizedDateString + "Z";
	const date = new Date(normalizedDateString);
	if (Number.isNaN(date.getTime())) return "";
	return date.toLocaleDateString(void 0, {
		year: "numeric",
		month: "long",
		day: "2-digit"
	});
};
const sanitizeFilenamePart = (value) => String(value ?? "").replace(/[\\/:*?"<>|]/g, "").replace(/\s+/g, " ").trim();
const getSubmissionDisplayFormName = (row, t) => {
	const overrideName = tryParseJsonObject(row?.formSubmission_Data)?.FormTemplateOverrides?.FormName;
	const baseName = row?.form_Name;
	return hasNonWhitespaceText(overrideName) ? overrideName.trim() : hasNonWhitespaceText(baseName) ? baseName.trim() : t("Untitled Form");
};
const getBrowserTimeZone = () => {
	try {
		return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
	} catch {
		return "UTC";
	}
};
const filterConfigByUrlField = {
	form_name: {
		agGridField: "form_Name",
		filterType: "text"
	},
	formsubmission_formid: {
		agGridField: "formSubmission_FormId",
		filterType: "text"
	},
	formsubmission_formversion: {
		agGridField: "formSubmission_FormVersion",
		filterType: "number"
	},
	form_description: {
		agGridField: "form_Description",
		filterType: "text"
	},
	formsubmission_userdisplayname: {
		agGridField: "formSubmission_UserDisplayName",
		filterType: "text"
	},
	formsubmission_status: {
		agGridField: "formSubmission_Status",
		filterType: "number"
	},
	formsubmission_initialcreatedon: {
		agGridField: "formSubmission_InitialCreatedOn",
		filterType: "date"
	},
	formsubmission_lastmodifiedon: {
		agGridField: "formSubmission_LastModifiedOn",
		filterType: "date"
	},
	formsubmission_submittedon: {
		agGridField: "formSubmission_SubmittedOn",
		filterType: "date"
	},
	formsubmission_duedate: {
		agGridField: "formSubmission_DueDate",
		filterType: "date"
	},
	formsubmission_isoverdue: {
		agGridField: "formSubmission_IsOverdue",
		filterType: "text"
	}
};
/**
* Maps your internal filter object structure (from URL processing)
* to the ag-Grid Filter Model structure.
* @param {Array<{searchField: string, searchOperator: number, searchValue: string}>} filterObjects
* @returns {object} ag-Grid Filter Model
*/
const mapUrlFiltersToAgGridModel = (filterObjects) => {
	if (!filterObjects || filterObjects.length === 0) return null;
	const agGridModel = {};
	filterObjects.forEach((filter) => {
		const { searchField, searchOperator, searchValue } = filter;
		const config = filterConfigByUrlField[searchField.toLocaleLowerCase()];
		if (!config) {
			console.warn(`No configuration found for URL filter field: ${searchField}. Filter ignored.`);
			return;
		}
		const agGridField = config.agGridField;
		const filterType = config.filterType;
		let type = "equals";
		switch (searchOperator) {
			case SqlFilterOperators.EQUALS:
				type = "equals";
				break;
			case SqlFilterOperators.NOT_EQUALS:
				type = "notEqual";
				break;
			case SqlFilterOperators.GREATER_THAN:
				type = "greaterThan";
				break;
			case SqlFilterOperators.LESS_THAN:
				type = "lessThan";
				break;
			case SqlFilterOperators.LIKE:
				type = "contains";
				break;
			default: type = "equals";
		}
		let filterValue = searchValue;
		if (!filterValue || filterValue.toLowerCase() === "undefined" || filterValue.toLowerCase() === "null") {
			console.warn(`Skipping filter for ${agGridField} due to invalid value: ${searchValue}`);
			return;
		}
		if (filterType == "date") agGridModel[agGridField] = {
			filterType,
			type,
			dateFrom: filterValue
		};
		else if (filterType == "text" && agGridField.toLocaleLowerCase() == "formsubmission_isoverdue") agGridModel[agGridField] = {
			filterType,
			type: filterValue
		};
		else agGridModel[agGridField] = {
			filterType,
			type,
			filter: filterValue
		};
	});
	return agGridModel;
};
const parseIdAndVersion = (input) => {
	const formSubmissionId = input.replace(/^form-submission-/, "");
	if (formSubmissionId.includes("all-forms-key")) return null;
	return formSubmissionId;
};
const getSubmissionStatusLabel = (node) => {
	switch (node?.data?.formSubmission_Status) {
		case UdpFormsSubmissionStatusEnum.InProgress: return "InProgress";
		case UdpFormsSubmissionStatusEnum.Created: return "Created";
		case UdpFormsSubmissionStatusEnum.Submitted: return "Submitted";
		default: return "";
	}
};
const getOverdueStatusLabel = (node) => {
	switch (node?.data?.formSubmission_IsOverdue) {
		case true: return "Overdue";
		default: return "";
	}
};
const gridFunctions = [
	{ name: "agGridSizeColumnsToFit" },
	{ name: "agGridAutoSizeColumns" },
	{ name: "agGridResetColumns" },
	{ name: "agGridHideShowColumns" },
	{ name: "agGridExport" },
	{ name: "openSavedViews" }
];
const statusMappingConfig = {
	Created: "info",
	InProgress: "warning",
	Submitted: "success",
	Overdue: "error"
};
const defaultGridOptions = {
	pagination: true,
	defaultColDef: {
		sortable: true,
		filter: true,
		resizable: true
	}
};
const UdpFormsSubmissionGrid = ({ isManagerMode = false, generic1 = void 0, generic2 = void 0, generic3 = void 0, formsRendererUrlPath = void 0, allFormTitle = void 0, menuTitle = void 0, onSideSheetPrimaryAction = void 0, enableDownloadPdfAction = true, paginationAutoPageSize = true }) => {
	const user = useUser();
	const tenant = useTenant();
	const history = useHistory();
	const location = useLocation();
	const { t } = useTranslation();
	const { enqueueSnackbar, closeSnackbar } = useSnackbar();
	const [innerMenuItemList, setInnerMenuItemList] = useState([]);
	const [formSubmissionViewDataRaw, setFormSubmissionViewDataRaw] = useState([]);
	const [formDataRaw, setFormDataRaw] = useState([]);
	const [isSidesheetOpen, setIsSidesheetOpen] = useState(false);
	const [selectedUdpFormInSideSheet, setSelectedUdpFormInSideSheet] = useState({});
	const [formSubmissionUrlSearchObjs, setFormSubmissionUrlSearchObjs] = useState([]);
	const [gridApi, setGridApi] = useState(null);
	const handleGridApiCallback = useCallback((api) => {
		setGridApi(api);
	}, []);
	const [containsDueDate, setContainsDueDate] = useState(false);
	const [dueDateValue, setDueDateValue] = useState(null);
	const [isPdfDownloadInProgress, setIsPdfDownloadInProgress] = useState(false);
	const isPdfDownloadInProgressRef = useRef(false);
	const initialFilterModel = useMemo(() => {
		return mapUrlFiltersToAgGridModel(formSubmissionUrlSearchObjs);
	}, [formSubmissionUrlSearchObjs]);
	const gridOptions = useMemo(() => {
		return {
			...defaultGridOptions,
			paginationAutoPageSize,
			overlayLoadingTemplate: `<UdpText variant="body1">Generating PDF...</UdpText>`
		};
	}, [paginationAutoPageSize, t]);
	useEffect(() => {
		if (gridApi && initialFilterModel) {
			gridApi.setFilterModel(initialFilterModel);
			gridApi.onFilterChanged();
		}
	}, [gridApi, initialFilterModel]);
	useEffect(() => {
		if (!gridApi) return;
		gridApi.refreshCells({
			force: true,
			columns: ["actions"]
		});
	}, [gridApi, isPdfDownloadInProgress]);
	useEffect(() => {
		if (!gridApi?.toggleLoadingOverlay) return;
		gridApi.toggleLoadingOverlay(isPdfDownloadInProgress);
	}, [gridApi, isPdfDownloadInProgress]);
	const consolidateAndSortFormsByFormId = useCallback((forms, submissions = []) => {
		const resultMap = /* @__PURE__ */ new Map();
		for (const item of forms) {
			const { id: formId, version: formVersion, name: formName, description: formDescription, initialCreatedOn } = item;
			if (!formId || formVersion == null) continue;
			const key = String(formId);
			const existing = resultMap.get(key);
			const versionNum = Number(formVersion) || 0;
			const ts = initialCreatedOn ? new Date(initialCreatedOn).getTime() : 0;
			const submissionCount = (submissions || []).filter((sub) => String(sub?.formSubmission_FormId) === key).length;
			if (!existing) resultMap.set(key, {
				id: key,
				formId,
				formVersion: versionNum,
				name: formName || t("Untitled Form"),
				submissionCount,
				description: formDescription || "",
				mostRecentCreatedOn: ts
			});
			else if (versionNum > (existing.formVersion || 0)) {
				existing.formVersion = versionNum;
				if (formName) existing.name = formName;
				if (formDescription) existing.description = formDescription;
			}
		}
		return Array.from(resultMap.values()).sort((a, b) => b.name.localeCompare(a.name));
	}, [t]);
	const fetchForms = useCallback(async () => {
		try {
			if (!tenant?.activeTenant?.tenantId) return;
			const filterElements = [];
			filterElements.push({
				searchField: "tenantId",
				searchOperator: "=",
				searchValue: tenant.activeTenant.tenantId
			});
			setFormDataRaw((await apiMutate(ConfigService.productV1ApiUrl, `UdpForm/search`, {
				method: "POST",
				data: {
					eagerLoad: false,
					getAll: true,
					filterElements
				}
			}, {}))?.data.pageList || []);
		} catch (e) {
			console.error("fetchForms error:", e);
		}
	}, [
		user,
		tenant,
		useCallback((submissions_0) => {
			const resultMap_0 = /* @__PURE__ */ new Map();
			for (const item_0 of submissions_0) {
				const { formSubmission_FormId: formId_0, formSubmission_FormVersion: formVersion_0, form_Name: formName_0, form_Description: formDescription_0, formSubmission_InitialCreatedOn: initialCreatedOn_0 } = item_0;
				if (!formId_0 || formVersion_0 == null) continue;
				const key_0 = `${formId_0}`;
				const existing_0 = resultMap_0.get(key_0);
				const versionNum_0 = Number(formVersion_0) || 0;
				const ts_0 = initialCreatedOn_0 ? new Date(initialCreatedOn_0).getTime() : 0;
				if (!existing_0) resultMap_0.set(key_0, {
					id: key_0,
					formId: formId_0,
					formVersion: versionNum_0,
					name: formName_0 || t("Untitled Form"),
					submissionCount: 1,
					description: formDescription_0 || "",
					mostRecentCreatedOn: ts_0
				});
				else {
					existing_0.submissionCount += 1;
					existing_0.mostRecentCreatedOn = Math.max(existing_0.mostRecentCreatedOn || 0, ts_0);
					if (versionNum_0 > (existing_0.formVersion || 0)) {
						existing_0.formVersion = versionNum_0;
						if (formName_0) existing_0.name = formName_0;
						if (formDescription_0) existing_0.description = formDescription_0;
					}
				}
			}
			return Array.from(resultMap_0.values()).sort((a_0, b_0) => b_0.mostRecentCreatedOn - a_0.mostRecentCreatedOn);
		}, [t])
	]);
	const getSearchMethodConfig = useCallback((formId_1) => {
		if (!tenant?.activeTenant?.tenantId) return;
		const filterElements_0 = [];
		if (!isManagerMode) filterElements_0.push({
			searchField: "formSubmission_unityUserId",
			searchOperator: "=",
			searchValue: user.id || ""
		});
		if (formId_1) filterElements_0.push({
			searchField: "formSubmission_formId",
			searchOperator: "=",
			searchValue: formId_1
		});
		if (generic1 !== void 0) filterElements_0.push({
			searchField: "formSubmission_generic1",
			searchOperator: "=",
			searchValue: generic1
		});
		if (generic2 !== void 0) filterElements_0.push({
			searchField: "formSubmission_generic2",
			searchOperator: "=",
			searchValue: generic2
		});
		if (generic3 !== void 0) filterElements_0.push({
			searchField: "formSubmission_generic3",
			searchOperator: "=",
			searchValue: generic3
		});
		filterElements_0.push({
			searchField: "form_tenantId",
			searchOperator: "=",
			searchValue: tenant?.activeTenant?.tenantId || ""
		});
		return {
			requestUrl: `${ConfigService.productV1ApiUrl}/UdpFormWithSubmissionsView/search`,
			customSearchObject: {
				eagerLoad: false,
				filterElements: filterElements_0,
				orderElements: [{
					sortColumn: "formSubmission_InitialCreatedOn",
					sortDirection: "DESC"
				}]
			}
		};
	}, [
		user,
		isManagerMode,
		tenant,
		generic1,
		generic2,
		generic3
	]);
	useCallback((formId_2, formVersion_1) => {
		return `${formsRendererUrlPath ? formsRendererUrlPath : "page/" + UdpPageEnums.Udp_Forms_Renderer_Page_Private}?udpf_formId=${encodeURIComponent(formId_2)}&udpf_formVersion=${encodeURIComponent(formVersion_1)}`;
	}, [formsRendererUrlPath]);
	const generateFormRendererUrlPathUsingSubmissionId = useCallback((submissionId) => {
		return `${formsRendererUrlPath ? formsRendererUrlPath : "page/" + UdpPageEnums.Udp_Forms_Renderer_Page_Private}?udpf_submissionId=${encodeURIComponent(submissionId)}`;
	}, [formsRendererUrlPath]);
	const getGridHeaderConfig = useCallback((formId_3, formVersion_2, formTitle) => {
		const config = { title: formTitle };
		if (!isManagerMode) config.primaryActionButton = {
			label: t("Submit New Form"),
			onClick: () => {
				if (formId_3 && formVersion_2) setSelectedUdpFormInSideSheet({
					value: `${formId_3}|${formVersion_2}`,
					label: formTitle
				});
				setIsSidesheetOpen(true);
			}
		};
		return config;
	}, [
		history,
		t,
		isManagerMode
	]);
	const columnDefs = [
		{
			headerName: "Form ID",
			field: "formSubmission_FormId",
			hide: true
		},
		{
			headerName: t("Name"),
			field: "form_Name",
			type: "text",
			sortable: true,
			valueGetter: (params) => {
				const row = params?.data;
				if (!row) return "";
				const overrideName = tryParseJsonObject(row.formSubmission_Data)?.FormTemplateOverrides?.FormName;
				if (hasNonWhitespaceText(overrideName)) return overrideName.trim();
				return row.form_Name ?? "";
			}
		},
		{
			headerName: t("Version"),
			field: "formSubmission_FormVersion",
			type: "number",
			sortable: true
		},
		{
			headerName: t("Description"),
			field: "form_Description",
			type: "text",
			sortable: true,
			hide: true,
			valueGetter: (params_0) => {
				const row_0 = params_0?.data;
				if (!row_0) return "";
				const overrideDescription = tryParseJsonObject(row_0.formSubmission_Data)?.FormTemplateOverrides?.FormDescription;
				if (hasNonWhitespaceText(overrideDescription)) return overrideDescription.trim();
				return row_0.form_Description ?? "";
			}
		},
		{
			headerName: t("Submitted By"),
			field: "formSubmission_UserDisplayName",
			type: "text",
			sortable: true
		},
		{
			headerName: t("Status"),
			filter: true,
			field: "formSubmission_Status",
			cellRenderer: "statusRenderer",
			cellRendererParams: {
				statusMappingConfig,
				getStatusValue: getSubmissionStatusLabel
			}
		},
		{
			headerName: t("Overdue Status"),
			field: "formSubmission_IsOverdue",
			cellDataType: "boolean",
			sortable: true,
			cellRenderer: "statusRenderer",
			cellRendererParams: {
				statusMappingConfig,
				getStatusValue: getOverdueStatusLabel
			}
		},
		{
			headerName: t("Created On"),
			field: "formSubmission_InitialCreatedOn",
			valueFormatter: (p) => p.value ? formatDateTime(p.value) : "",
			sortable: true,
			cellDataType: "dateTimeString"
		},
		{
			headerName: t("Last Modified On"),
			field: "formSubmission_LastModifiedOn",
			valueFormatter: (p_0) => p_0.value ? formatDateTime(p_0.value) : "",
			sortable: true,
			cellDataType: "dateTimeString"
		},
		{
			headerName: t("Submitted On"),
			field: "formSubmission_SubmittedOn",
			valueFormatter: (p_1) => p_1.value ? formatDateTime(p_1.value) : "",
			sortable: true,
			cellDataType: "dateTimeString"
		},
		{
			headerName: t("Due On"),
			field: "formSubmission_DueDate",
			valueFormatter: (p_2) => p_2.value ? formatDateTime(p_2.value) : "",
			sortable: true,
			cellDataType: "dateTimeString"
		},
		{
			field: "actions",
			cellRenderer: "actionsRenderer",
			cellRendererParams: { actionList: [{
				id: 0,
				iconName: "view",
				title: t("Open This Submission"),
				handleOnClick: (e_0, params_1) => {
					history.push(`${formsRendererUrlPath ? formsRendererUrlPath : "/page/" + UdpPageEnums.Udp_Forms_Renderer_Page_Private}?udpf_submissionId=${params_1?.data?.formSubmission_Id}`);
				}
			}, ...enableDownloadPdfAction ? [{
				id: 1,
				iconName: "documentPdf",
				title: t("Download Report"),
				checkDisabled: () => isPdfDownloadInProgress,
				handleOnClick: async (e_1, params_2) => {
					if (isPdfDownloadInProgressRef.current) return;
					isPdfDownloadInProgressRef.current = true;
					setIsPdfDownloadInProgress(true);
					try {
						const row_1 = params_2?.data;
						const browserTimeZone = getBrowserTimeZone();
						const blob = (await apiMutate(ConfigService.productV1ApiUrl, `udpFormSubmission/${row_1?.formSubmission_Id}/report?timeZoneId=${encodeURIComponent(browserTimeZone)}`, {
							method: "GET",
							responseType: "blob"
						}, {})).data;
						const reportName = getSubmissionDisplayFormName(row_1, t);
						const submissionOwner = row_1?.formSubmission_UserDisplayName || t("Unknown User");
						const submittedLabel = Number(row_1?.formSubmission_Status) === UdpFormsSubmissionStatusEnum.Submitted ? formatDateForFilename(row_1?.formSubmission_SubmittedOn) || t("Submitted") : t("Not Submitted");
						const filename = `${sanitizeFilenamePart(reportName)} - ${sanitizeFilenamePart(submissionOwner)} - ${sanitizeFilenamePart(submittedLabel)}.pdf`;
						const blobUrl = window.URL.createObjectURL(blob);
						const link = document.createElement("a");
						link.href = blobUrl;
						link.download = filename;
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
						window.URL.revokeObjectURL(blobUrl);
					} catch (error) {
						console.error("Error downloading report:", error);
						enqueueSnackbar(t("Error downloading report"), {
							variant: "error",
							anchorOrigin: {
								vertical: "top",
								horizontal: "center"
							}
						});
					} finally {
						isPdfDownloadInProgressRef.current = false;
						setIsPdfDownloadInProgress(false);
					}
				}
			}] : []] }
		}
	];
	const handleSidesheetPrimaryClick = async () => {
		try {
			const [id, versionStr] = (selectedUdpFormInSideSheet?.value || "").split("|");
			const version = Number(versionStr || 0);
			if (!id || !version) {
				console.warn("Invalid selection:", selectedUdpFormInSideSheet);
				setIsSidesheetOpen(false);
				return;
			}
			const fd = new FormData();
			fd.append("FormId", id);
			fd.append("FormVersion", String(version));
			fd.append("Status", String(UdpFormsSubmissionStatusEnum.Created));
			fd.append("Data", JSON.stringify({}));
			if (dueDateValue) fd.append("DueDate", toUtcIsoAtLocalEndOfDay(dueDateValue));
			if (generic1 !== void 0) fd.append("Generic1", String(generic1));
			if (generic2 !== void 0) fd.append("Generic2", String(generic2));
			if (generic3 !== void 0) fd.append("Generic3", String(generic3));
			const newSubmissionId = (await apiMutate(ConfigService.productV1ApiUrl, `UdpFormSubmission`, {
				method: "POST",
				data: fd
			}, {}))?.data?.id;
			setIsSidesheetOpen(false);
			const urlPath = generateFormRendererUrlPathUsingSubmissionId(newSubmissionId);
			history.push(urlPath);
		} catch (e_2) {
			console.error("handleSidesheetPrimaryClick error:", e_2);
			enqueueSnackbar(t("Error creating a new form."), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		}
	};
	const handleSideSheetDueDateToggleChange = useCallback((checked) => {
		setContainsDueDate(checked);
		if (!checked) setDueDateValue(null);
	}, []);
	const handleDueDateChange = useCallback((e_3) => {
		const next = e_3?.target?.value;
		setDueDateValue(next);
	}, []);
	const handleSideSheetClosed = () => {
		setSelectedUdpFormInSideSheet({});
		setIsSidesheetOpen(false);
		setContainsDueDate(false);
		setDueDateValue(null);
	};
	const selectableItems = useMemo(() => {
		const map = /* @__PURE__ */ new Map();
		for (const f of formDataRaw || []) {
			const formType = f.form_Type ?? f.formType ?? f.type;
			if (Number(formType) !== 1) continue;
			const formId_4 = f.id ?? f.form_Id ?? f.formId ?? String(f?.Id ?? "");
			const version_0 = Number(f.version ?? f.form_Version ?? f.formVersion ?? 0);
			const name = f.name ?? f.form_Name ?? f.formName ?? f.Form_Name ?? f.displayName ?? t("Untitled Form");
			const description = f.description ?? f.form_Description ?? "";
			const existing_1 = map.get(formId_4);
			if (!existing_1 || version_0 > existing_1.version) map.set(formId_4, {
				id: formId_4,
				name,
				version: version_0,
				description
			});
		}
		return Array.from(map.values()).sort((a_1, b_1) => b_1.version - a_1.version);
	}, [formDataRaw, t]);
	const selectorOptions = useMemo(() => {
		return (selectableItems || []).map((s) => ({
			value: `${s.id}|${s.version}`,
			label: s.version ? `${s.name} (v${s.version})` : s.name
		}));
	}, [selectableItems]);
	const handleSelectedUdpFormInSideSheetChange = (event, newValue) => {
		if (newValue !== null) setSelectedUdpFormInSideSheet(newValue);
	};
	const getMainGridContent = ({ selectedNode, menuItemsList, idMap, classes }) => {
		if (!selectedNode) return /* @__PURE__ */ React.createElement(PageLoading, null);
		const formId_5 = parseIdAndVersion(selectedNode.id);
		const found = innerMenuItemList.find((form) => form.formId == formId_5);
		const formTitle_0 = `${found?.name}` || "Unknown Form";
		const newestFormVersion = formDataRaw.filter((formObj) => formObj.id == formId_5).reduce((acc, curr) => {
			return Math.max(acc, curr.version);
		}, null);
		return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SideSheet, {
			open: isSidesheetOpen,
			title: t("Submit New Form"),
			position: "right",
			width: "30%",
			buttonLabel: t("New"),
			buttonOneDisabled: !selectedUdpFormInSideSheet?.value || containsDueDate && !dueDateValue,
			onSubmit: handleSidesheetPrimaryClick,
			onClose: handleSideSheetClosed
		}, /* @__PURE__ */ React.createElement(FormControlLabel, {
			control: /* @__PURE__ */ React.createElement(Switch, {
				size: "small",
				onChange: (e_4) => handleSideSheetDueDateToggleChange(Boolean(e_4?.target?.checked))
			}),
			label: "Set a Due Date",
			style: { marginLeft: 0 }
		}), containsDueDate ? /* @__PURE__ */ React.createElement(TextField, {
			label: t("Due Date"),
			type: "date",
			variant: "outlined",
			size: "small",
			InputLabelProps: { shrink: true },
			value: dueDateValue,
			onChange: handleDueDateChange,
			helperText: t("Set a due date at the end-of-day based on your local time.")
		}) : null, !(found?.id && newestFormVersion) && /* @__PURE__ */ React.createElement(Autocomplete, {
			options: selectorOptions,
			getOptionLabel: (selectedOption) => selectedOption.label,
			onChange: handleSelectedUdpFormInSideSheetChange,
			value: selectedUdpFormInSideSheet,
			disableClearable: true,
			size: "small",
			renderInput: (params_3) => /* @__PURE__ */ React.createElement(TextField, {
				...params_3,
				label: t("Choose a Form"),
				variant: "outlined"
			})
		})), /* @__PURE__ */ React.createElement(SearchMethodUdpGrid, {
			searchMethodConfig: getSearchMethodConfig(formId_5),
			columnDefs,
			gridId: isManagerMode ? UdpFormsSubmissionGridIds.ManagerId : UdpFormsSubmissionGridIds.ResponderId,
			gridOptions,
			gridHeaderConfig: getGridHeaderConfig(formId_5, newestFormVersion, formTitle_0),
			gridFunctions,
			gridApiCallback: handleGridApiCallback
		}));
	};
	useEffect(() => {
		if (!tenant?.activeTenant?.tenantId) return;
		setFormSubmissionUrlSearchObjs(parseSearchParamsIntoFilterObjects());
		let cancelled = false;
		(async () => {
			try {
				let filterElements_1 = [];
				filterElements_1.push({
					searchField: "Form_TenantId",
					searchOperator: "=",
					searchValue: tenant.activeTenant.tenantId
				});
				if (!isManagerMode) filterElements_1.push({
					searchField: "FormSubmission_UnityUserId",
					searchOperator: "=",
					searchValue: user.id
				});
				if (generic1 !== void 0) filterElements_1.push({
					searchField: "formSubmission_generic1",
					searchOperator: "=",
					searchValue: generic1
				});
				if (generic2 !== void 0) filterElements_1.push({
					searchField: "formSubmission_generic2",
					searchOperator: "=",
					searchValue: generic2
				});
				if (generic3 !== void 0) filterElements_1.push({
					searchField: "formSubmission_generic3",
					searchOperator: "=",
					searchValue: generic3
				});
				const formSubmissionViewSearchResponse_0 = await apiMutate(ConfigService.productV1ApiUrl, `UdpFormWithSubmissionsView/search`, {
					method: "POST",
					data: {
						eagerLoad: false,
						getAll: true,
						filterElements: filterElements_1
					}
				}, {});
				if (cancelled) return;
				setFormSubmissionViewDataRaw((formSubmissionViewSearchResponse_0?.data.pageList || []).filter((submission) => submission.form_TenantId === tenant.activeTenant.tenantId));
				await fetchForms();
			} catch (err) {
				console.error("fetching submissions/forms failed", err);
			}
		})();
		return () => {
			cancelled = true;
		};
	}, [
		location.search,
		tenant?.activeTenant?.tenantId,
		generic1,
		generic2,
		generic3,
		isManagerMode,
		user?.id,
		fetchForms
	]);
	useEffect(() => {
		const innerMenuList = consolidateAndSortFormsByFormId(formDataRaw || [], formSubmissionViewDataRaw || []);
		innerMenuList.unshift({
			id: "all-forms-key",
			name: allFormTitle ?? t(isManagerMode ? t("All Form Submissions") : t("All My Form Submissions")),
			submissionCount: formSubmissionViewDataRaw?.length || 0
		});
		setInnerMenuItemList(innerMenuList);
	}, [
		formSubmissionViewDataRaw,
		isManagerMode,
		consolidateAndSortFormsByFormId,
		formDataRaw,
		t,
		allFormTitle
	]);
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(CustomMenuPage, {
		menuTitle: menuTitle ?? t("Forms"),
		items: innerMenuItemList,
		idPrefix: "form-submission",
		showItemCount: true,
		itemCountAccessor: (item_1) => item_1?.submissionCount ?? 0,
		mainContent: ({ selectedNode: selectedNode_0, menuItemsList: menuItemsList_0, idMap: idMap_0, classes: classes_0 }) => {
			return /* @__PURE__ */ React.createElement("div", null, getMainGridContent({
				selectedNode: selectedNode_0,
				menuItemsList: menuItemsList_0,
				idMap: idMap_0,
				classes: classes_0
			}));
		}
	}));
};
//#endregion
export { UdpFormsSubmissionGrid };

//# sourceMappingURL=UdpFormsSubmissionGrid.mjs.map