import { FluentIconButton } from "../inputs/buttons/FluentIconButton.mjs";
import { StandardTitle } from "../dataDisplay/typography/StandardTitle.mjs";
import { AmbientCard } from "../surfaces/cards/AmbientCard/AmbientCard.mjs";
import { AmbientGridTemplate } from "../templates/deprecated/AmbientGridTemplate/AmbientGridTemplate.mjs";
import { FluentTextField } from "../inputs/textField/FluentTextField.mjs";
import { useAuthedUser } from "../../utilities/auth/useAuthedUser.mjs";
import { generateGeoJsonList, getLayer } from "./utilities/MapUtilities.mjs";
import ListView from "./ui/ListView.mjs";
import ActionsRenderer from "./ui/ActionsRenderer.mjs";
import { UdpMapComponent } from "../maps/UdpMapComponent.mjs";
import { UdpMapToolbar } from "../maps/UdpMapToolbar.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Grid, lighten, makeStyles } from "@material-ui/core";
import clsx from "clsx";
import { ChromeCloseIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
import { isArray, isObject, startCase } from "lodash-es";
import { Circle, Fill, Icon, Stroke, Style } from "ol/style";
import { transform } from "ol/proj";
import proj4 from "proj4";
import { register } from "ol/proj/proj4";
import TruckIcon from "../../assets/unityIcons/TruckIcon.svg";
//#region src/UI/mapLayout/MapLayout.jsx
const useStyles = makeStyles((theme) => ({
	fullHeight: {
		height: "73vh",
		backgroundColor: lighten(theme.palette.primary.light, .7),
		overflow: "auto"
	},
	contentWrapper: { display: "flex" },
	detailSheetHeader: {
		display: "flex",
		backgroundColor: theme.palette.background.paper,
		padding: theme.spacing(1),
		alignItems: "center",
		gap: theme.spacing(1.5)
	},
	detailSheetBody: { padding: theme.spacing(2) },
	detailTitle: { marginTop: 0 },
	leftColumn: {
		overflow: "auto",
		backgroundColor: lighten(theme.palette.primary.light, .7)
	},
	listViewWrapper: { position: "relative" },
	zoomControl: {
		left: "auto",
		right: theme.spacing(.8),
		top: theme.spacing(5)
	}
}));
const styles = {
	Point: [new Style({
		image: new Icon({
			anchor: [.17, 48],
			anchorXUnits: "fraction",
			anchorYUnits: "pixels",
			src: TruckIcon,
			scale: .3
		}),
		zIndex: 1
	}), new Style({
		image: new Circle({
			stroke: new Stroke({
				color: "#0F62FE",
				width: 1
			}),
			fill: new Fill({ color: "#FFFFFF" }),
			radius: 20,
			scale: 1.1
		}),
		zIndex: 0
	})],
	LineString: new Style({
		stroke: new Stroke({
			color: "#0F62FE",
			width: 4
		}),
		zIndex: 0
	})
};
const MapLayout = (props) => {
	const { data, initialSelectedLayers, shellContext, sideSheetTitle, cardConfig, noRightPanelPadding = false, isGeoJsonFormat = true, geoJsonMappingConfig, position = "default", showMap = true, showList, showGrid = true, getSelectedFeatures, getSelectedLayers, getSelectedViewItemData, rightSectionPanel, rightSectionPanelTitle, rightSectionPanelState, setRightSectionPanelState, overrideDetailRightSection = false, layerOptions, layerKeySeparator = "", statisticsList, hideZeroValueStats, defaultTileOptionName, hideTileSelection, filterPanel, filterCallback, selectedFeaturesActionPanel, refreshEvent, refreshButtonTooltip, readOnlyMap, addFeaturePanelConfig, noWrapPrimaryText, hideListView = false, listFilter, listViewCardConfig, listViewDetailsEvent, listViewChipConfig, popoverDetailsEvent, popoverPrimaryActions, popoverMoreIconButtonActions, getMessagePopover, getMessageIconPopover, hideMessageIconPopover, popoverWidth, enableViewFeature = true, enableDeleteFeature, handleDeleteFeature, enableEditFeature, handleEditFeature, mapTitle = "", getMapFeatureStyles, getSelectedFeatureStyles, tileLayersOptions, imageLayersOptions, mapZoom, mapCenter, mapProjection, addInteractions, selectedPin, mapHeight = "45vh", addressBar, mapDataProjection, crs, layerKeys, mapFilter, showZoomControl, readOnlyLayers, layerRoles, getVectorLayerSources, enableAddNewFeature, addMultipleFeatures = false, enableSplitFeature, handleAddNewFeatures, handleSplitFeature, handleGetZoomExtent, minZoom, maxZoom, gridTitle, columnDefs, groupingData, frameworkComponents, primaryActionButton, loading, rowNodeIdName, gridHeight = "50vh", paginationPageSize, onSearch, onRowSelected, rowModelType, api, columnApi, gridReady, onCellClicked, gridFilter, ...otherGridProps } = props;
	const [selectedFeatureProperties, setSelectedFeatureProperties] = useState();
	const [showDetails, setShowDetails] = useState(false);
	const [selectedItemData, setSelectedItemData] = useState();
	const [definedProj, setDefinedProj] = useState(false);
	const [enableDragBox, setEnableDragBox] = useState(false);
	const [dataUpdateCount, setDataUpdateCount] = useState(0);
	const [map, setMap] = useState(null);
	const [filteredLayerOptions, setFilterLayerOptions] = useState();
	const [bulkSelectionActive, setBulkSelectionActive] = useState(false);
	const [splitActive, setSplitActive] = useState(false);
	const [selectedFeatureCoordinates, setSelectedFeatureCoordinates] = useState();
	const [addActive, setAddActive] = useState(false);
	const [selectedFeatureIdExternal, setSelectedFeatureIdExternal] = useState();
	const [currentCenter, setCurrentCenter] = useState(mapCenter ?? [0, 0]);
	const [selectedLayers, setSelectedLayers] = useState([]);
	const classes = useStyles();
	const user = useAuthedUser();
	const { t } = useTranslation();
	useEffect(() => {
		if (crs?.length > 0) {
			proj4.defs(crs);
			register(proj4);
			setDefinedProj(true);
		}
	}, [crs]);
	useEffect(() => {
		if (getSelectedLayers) getSelectedLayers(selectedLayers);
	}, [getSelectedLayers, selectedLayers]);
	useEffect(() => {
		if (getSelectedViewItemData) getSelectedViewItemData(selectedItemData);
	}, [getSelectedViewItemData, selectedItemData]);
	useEffect(() => {
		if (!data) return;
		if (dataUpdateCount === 0) setDataUpdateCount(dataUpdateCount + 1);
		if (dataUpdateCount === 1) setSelectedFeatureProperties(null);
	}, [data, dataUpdateCount]);
	const filteredData = useMemo(() => {
		if (!data) return [];
		const formattedData = isGeoJsonFormat ? data : generateGeoJsonList(data, geoJsonMappingConfig);
		if (filterPanel && filterCallback) return filterCallback(formattedData);
		return formattedData;
	}, [
		data,
		filterCallback,
		filterPanel,
		geoJsonMappingConfig,
		isGeoJsonFormat
	]);
	const gridData = useMemo(() => {
		return filteredData?.filter((obj) => {
			const layerKey = getLayer(layerKeys, layerKeySeparator, obj);
			if (layerRoles?.[layerKey]) return layerRoles[layerKey]?.some((roleId) => user.roleIds?.includes(roleId));
			return true;
		}).map((obj) => ({
			id: obj.id,
			...obj.properties
		}));
	}, [
		filteredData,
		layerKeySeparator,
		layerKeys,
		layerRoles,
		user.roleIds
	]);
	const filteredGridData = useMemo(() => {
		if (gridFilter) return gridFilter(gridData);
		return gridData;
	}, [gridData, gridFilter]);
	const filteredListData = useMemo(() => {
		if (listFilter) return listFilter(gridData);
		return gridData;
	}, [gridData, listFilter]);
	useEffect(() => {
		if (crs?.length > 0 && !definedProj) return;
		if (filteredData?.[0]?.geometry?.coordinates && mapProjection && mapDataProjection) setCurrentCenter(transform(isArray(filteredData?.[0]?.geometry?.coordinates[0]) ? filteredData?.[0]?.geometry?.coordinates[0] : filteredData?.[0]?.geometry?.coordinates, mapDataProjection, mapProjection));
	}, [
		filteredData,
		mapDataProjection,
		mapProjection,
		definedProj,
		crs
	]);
	const getStyles = useCallback((feature) => {
		return styles[feature.getGeometry().getType()] ?? new Style();
	}, []);
	const handleViewDetailsFromPopover = useCallback((data) => {
		const featureProperties = data?.selectedFeature?.getProperties();
		if (popoverDetailsEvent) {
			popoverDetailsEvent(featureProperties);
			return;
		}
		if (setRightSectionPanelState) setRightSectionPanelState(false);
		setShowDetails(true);
		setSelectedItemData(featureProperties);
		if (shellContext) shellContext.setInquiryMenuToggle(false);
	}, [
		popoverDetailsEvent,
		setRightSectionPanelState,
		shellContext
	]);
	const handleCloseDetailSheet = useCallback(() => {
		setShowDetails(false);
		if (setRightSectionPanelState) setRightSectionPanelState(false);
		setSelectedItemData(null);
	}, [setRightSectionPanelState]);
	const handleViewDetailsFromList = useCallback((data) => {
		setShowDetails(true);
		if (setRightSectionPanelState) setRightSectionPanelState(false);
		setSelectedItemData(data);
		if (shellContext) shellContext.setInquiryMenuToggle(false);
	}, [setRightSectionPanelState, shellContext]);
	const itemDetails = useMemo(() => {
		if (selectedItemData && !overrideDetailRightSection && !rightSectionPanelState) return Object.entries(selectedItemData).filter(([key, value]) => "geometry" !== key && !isObject(value) && !isArray(value)).map(([key, value]) => {
			return /* @__PURE__ */ React.createElement(FluentTextField, {
				label: startCase(key),
				value,
				InputProps: { readOnly: true }
			});
		});
	}, [
		overrideDetailRightSection,
		rightSectionPanelState,
		selectedItemData
	]);
	const gridColumnDefinition = useMemo(() => {
		if (!columnDefs) return;
		if (frameworkComponents?.actionsRenderer) return columnDefs;
		else return [...columnDefs, {
			headerName: t("Actions"),
			field: "actions",
			suppressSizeToFit: true,
			minWidth: 100,
			maxWidth: 125,
			cellRenderer: "actionsRenderer",
			cellRendererParams: { openView: (data) => handleViewDetailsFromList(data) },
			sortable: false
		}];
	}, [columnDefs, frameworkComponents]);
	const detailSheetHeight = useMemo(() => {
		if (!showGrid) return "73vh";
		else if (showGrid && !showMap) return `calc(67vh + 6vh)`;
		else return `calc(${mapHeight} + ${gridHeight} + 6vh)`;
	}, [
		gridHeight,
		mapHeight,
		showGrid,
		showMap
	]);
	const handleSelectLayers = (e) => {
		setSelectedLayers(e);
	};
	const handleSelectMarker = useCallback((data) => {
		setSelectedFeatureIdExternal(data?.id);
	}, []);
	const handleOnCellClicked = useCallback((params) => {
		if (onCellClicked) onCellClicked(params);
		if (!params?.node?.group && params?.colDef?.field !== "actions") handleSelectMarker(params?.data);
	}, [handleSelectMarker, onCellClicked]);
	const listView = useMemo(() => {
		if (hideListView) return;
		return /* @__PURE__ */ React.createElement(ListView, {
			data: filteredListData ?? [],
			listViewConfig: listViewCardConfig ?? cardConfig,
			noWrapPrimaryText,
			viewEvent: listViewDetailsEvent ?? handleViewDetailsFromList,
			showMarkerEvent: handleSelectMarker,
			chipConfig: listViewChipConfig
		});
	}, [
		cardConfig,
		filteredListData,
		handleSelectMarker,
		handleViewDetailsFromList,
		hideListView,
		listViewCardConfig,
		listViewChipConfig,
		listViewDetailsEvent,
		noWrapPrimaryText
	]);
	const handleSetSelectedFeatureProperties = useCallback((currentFeature) => {
		if (currentFeature) {
			let featureProperties = currentFeature?.getProperties();
			setSelectedFeatureCoordinates(currentFeature.getGeometry().getCoordinates());
			setSelectedFeatureProperties(featureProperties);
		}
	}, []);
	const handleCloseFeaturePopover = useCallback(() => {
		setSelectedFeatureIdExternal(null);
	}, []);
	const handleSetMapComponent = useCallback((value) => {
		setMap(value);
	}, []);
	const mapComponent = useMemo(() => {
		return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, {
			item: true,
			xs: 3,
			style: { display: !hideListView && showList ? "block" : "none" }
		}, /* @__PURE__ */ React.createElement("div", { className: clsx(classes.fullHeight, classes.listViewWrapper) }, listView)), /* @__PURE__ */ React.createElement(Grid, {
			item: true,
			xs: showList ? 9 : 12
		}, /* @__PURE__ */ React.createElement(UdpMapComponent, {
			map,
			handleSetMapComponent,
			data,
			isGeoJsonFormat,
			geoJsonMappingConfig,
			enableZoom: showZoomControl,
			mapZoom,
			mapCenter: currentCenter,
			mapHeight,
			crs,
			mapProjection,
			mapDataProjection,
			getFilteredMapData: mapFilter,
			getVectorLayerSources,
			getFeatureStyles: getMapFeatureStyles ?? getStyles,
			getSelectedFeatureStyles,
			filterPanel,
			filterPanelCallback: filterCallback,
			enableTileSelection: !hideTileSelection,
			tileLayersOptions,
			defaultTileOptionName,
			layerOptions,
			initialSelectedLayers,
			bulkSelectedFeaturesActionPanel: selectedFeaturesActionPanel,
			handleSetSelectedFeaturesOnBulkSelect: getSelectedFeatures,
			filterLayersByRole: layerRoles?.length > 0,
			layerKeys,
			layerKeySeparator,
			user,
			layerRoles,
			filteredLayerOptionsByRole: filteredLayerOptions,
			handleSetFilteredLayerOptionsByRole: setFilterLayerOptions,
			enableViewFeature,
			handleViewFeature: handleViewDetailsFromPopover,
			bulkSelectionActive,
			splitActive,
			enableDragBox,
			selectedFeatureCoordinates,
			selectedFeatureProperties,
			handleSetSelectedFeatureProperties,
			enableAddNewFeature: addActive,
			readOnlyLayers,
			selectedFeatureIdExternal,
			additionalOnclosePopover: handleCloseFeaturePopover,
			popoverPrimaryActions,
			popoverMoreIconButtonActions,
			getMessagePopover,
			getMessageIconPopover,
			hideMessageIconPopover,
			popoverCardConfig: cardConfig,
			selectedLayers,
			handleSetSelectedLayers: handleSelectLayers,
			handleGetZoomExtent,
			minZoom,
			maxZoom
		}))));
	}, [
		addActive,
		bulkSelectionActive,
		cardConfig,
		classes.fullHeight,
		classes.listViewWrapper,
		crs,
		currentCenter,
		data,
		defaultTileOptionName,
		enableDragBox,
		enableViewFeature,
		filterCallback,
		filterPanel,
		filteredLayerOptions,
		geoJsonMappingConfig,
		getMapFeatureStyles,
		getMessageIconPopover,
		getMessagePopover,
		getSelectedFeatureStyles,
		getSelectedFeatures,
		getStyles,
		getVectorLayerSources,
		handleCloseFeaturePopover,
		handleGetZoomExtent,
		handleSetMapComponent,
		handleSetSelectedFeatureProperties,
		handleViewDetailsFromPopover,
		hideListView,
		hideMessageIconPopover,
		hideTileSelection,
		initialSelectedLayers,
		isGeoJsonFormat,
		layerKeySeparator,
		layerKeys,
		layerOptions,
		layerRoles,
		listView,
		map,
		mapDataProjection,
		mapFilter,
		mapHeight,
		mapProjection,
		mapZoom,
		maxZoom,
		minZoom,
		popoverMoreIconButtonActions,
		popoverPrimaryActions,
		readOnlyLayers,
		selectedFeatureCoordinates,
		selectedFeatureIdExternal,
		selectedFeatureProperties,
		selectedFeaturesActionPanel,
		selectedLayers,
		showList,
		showZoomControl,
		splitActive,
		tileLayersOptions,
		user
	]);
	const gridComponent = useMemo(() => {
		return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(AmbientGridTemplate, {
			title: gridTitle,
			data: filteredGridData,
			columnDefs: gridColumnDefinition,
			groupingData,
			frameworkComponents: {
				actionsRenderer: ActionsRenderer,
				...frameworkComponents
			},
			primaryActionButton,
			loading,
			rowNodeIdName,
			height: showGrid && !showMap ? "67vh" : gridHeight,
			paginationPageSize,
			onSearch,
			onRowSelected,
			rowModelType,
			api,
			columnApi,
			gridReady,
			dynamicSizing: true,
			onCellClicked: handleOnCellClicked,
			...otherGridProps
		}));
	}, [
		api,
		columnApi,
		filteredGridData,
		frameworkComponents,
		gridColumnDefinition,
		gridHeight,
		gridReady,
		gridTitle,
		groupingData,
		handleOnCellClicked,
		loading,
		onRowSelected,
		onSearch,
		otherGridProps,
		paginationPageSize,
		primaryActionButton,
		rowModelType,
		rowNodeIdName,
		showGrid,
		showMap
	]);
	const mapGrid = useMemo(() => {
		if (position === "gridOnTop") return /* @__PURE__ */ React.createElement("div", null, showGrid && gridComponent, showMap && mapComponent);
		return /* @__PURE__ */ React.createElement("div", null, showMap && mapComponent, showGrid && gridComponent);
	}, [
		gridComponent,
		mapComponent,
		position,
		showGrid,
		showMap
	]);
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(UdpMapToolbar, {
		map,
		mapTitle,
		mapProjection,
		getFeatureStyles: getMapFeatureStyles,
		getSelectedFeatureStyles,
		filterPanel,
		filterPanelCallback: filterCallback,
		enableTileSelection: !hideTileSelection,
		tileLayersOptions,
		defaultTileOptionName,
		layerOptions,
		initialSelectedLayers,
		bulkSelectedFeaturesActionPanel: selectedFeaturesActionPanel,
		handleSetSelectedFeaturesOnBulkSelect: getSelectedFeatures,
		handleSetSelectedFeatureOnSelect: getSelectedViewItemData,
		handleRefresh: refreshEvent,
		refreshButtonTooltip,
		readOnlyMap,
		enableAdd: enableAddNewFeature,
		handleAddNewFeatures,
		addMultipleFeatures,
		enableSplitFeature,
		handleSplitFeature,
		handleSetSelectedFeatureProperties,
		filteredLayerOptionsByRole: filteredLayerOptions,
		handleSetBulkSelectionActive: setBulkSelectionActive,
		enableDragBox,
		handleSetEnableDragBox: setEnableDragBox,
		splitActive,
		handleSetSplitActive: setSplitActive,
		enableAddNewFeature: addActive,
		handleEnableAddNewFeature: setAddActive,
		readOnlyLayers,
		selectedLayers,
		handleSetSelectedLayers: handleSelectLayers,
		addFeaturePanelConfig
	}), /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, {
		item: true,
		...showDetails || rightSectionPanelState ? {
			xs: 7,
			sm: 9
		} : { xs: 12 }
	}, mapGrid), (showDetails || rightSectionPanelState) && /* @__PURE__ */ React.createElement(Grid, {
		item: true,
		xs: 5,
		sm: 3,
		className: classes.leftColumn,
		style: { maxHeight: detailSheetHeight }
	}, /* @__PURE__ */ React.createElement("div", { className: classes.detailSheetHeader }, /* @__PURE__ */ React.createElement(FluentIconButton, {
		onClick: handleCloseDetailSheet,
		icon: ChromeCloseIcon
	}), /* @__PURE__ */ React.createElement(StandardTitle, { className: classes.detailTitle }, rightSectionPanelTitle ?? t("Details"))), /* @__PURE__ */ React.createElement("div", { className: noRightPanelPadding ? null : classes.detailSheetBody }, rightSectionPanel && (rightSectionPanelState || showDetails && overrideDetailRightSection) && rightSectionPanel, showDetails && itemDetails && /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, itemDetails)))));
};
//#endregion
export { MapLayout };

//# sourceMappingURL=MapLayout.mjs.map