import { Button, Stack } from "@mui/material";
import { useMap } from "react-leaflet";

import { MAP_OBJECT_ZOOM } from "@/constants";
import { isNumber } from "@/services/math";
import {
	ButtonGroup,
	MapControlContainer,
	MinusIcon,
	PlusIcon,
} from "@/shared";

import { useUserSettings } from "../hooks/useUserSettings";
import { useWatcherStore } from "../store/watcher.store";

export function ZoomControls() {
	const map = useMap();
	const { assets, commonAlarms, groups } = useWatcherStore();
	const { settings } = useUserSettings();

	function zoomIn() {
		map.zoomIn();
	}

	function zoomOut() {
		map.zoomOut();
	}

	function zoomDefault() {
		const strategy = settings?.positioningStrategy || "center_of_all_objects";
		
		// Получаем активы с координатами
		const assetsWithCoordinates = assets.filter(
			(asset) => 
				isNumber(asset.latitude).is && 
				isNumber(asset.longitude).is
		);

		if (assetsWithCoordinates.length === 0) {
			// Если нет активов - используем дефолтный зум без изменения центра
			map.setZoom(MAP_OBJECT_ZOOM);
			return;
		}

		let targetPosition: [number, number] | null = null;

		switch (strategy) {
			case "active_alarm_object":
				// Переход к активному объекту с тревогой
				const assetsWithAlarms = assetsWithCoordinates.filter(asset =>
					commonAlarms.some(alarm => alarm.event.assetId === asset.id)
				);
				
				if (assetsWithAlarms.length > 0) {
					const targetAsset = assetsWithAlarms[0];
					targetPosition = [targetAsset.latitude!, targetAsset.longitude!];
				}
				break;

			case "asset_group_center":
				// Автоцентрирование по группе объектов
				if (settings?.assetGroupId) {
					const groupAssets = assetsWithCoordinates.filter(asset =>
						asset.groupIds.includes(settings.assetGroupId!)
					);
					
					if (groupAssets.length > 0) {
						const latitudes = groupAssets.map(a => a.latitude!);
						const longitudes = groupAssets.map(a => a.longitude!);
						
						const centerLat = (Math.min(...latitudes) + Math.max(...latitudes)) / 2;
						const centerLng = (Math.min(...longitudes) + Math.max(...longitudes)) / 2;
						
						targetPosition = [centerLat, centerLng];
					}
				}
				break;

			case "manual_start_position":
				// Ручной выбор стартовой позиции карты
				if (settings?.manualLatitude && settings?.manualLongitude) {
					targetPosition = [settings.manualLatitude, settings.manualLongitude];
				}
				break;

			case "current_view_center":
				// Использовать текущий центр области просмотра
				const center = map.getCenter();
				targetPosition = [center.lat, center.lng];
				break;

			case "center_of_all_objects":
			default:
				// Центрировать по середине всех объектов
				const latitudes = assetsWithCoordinates.map(a => a.latitude!);
				const longitudes = assetsWithCoordinates.map(a => a.longitude!);
				
				const centerLat = (Math.min(...latitudes) + Math.max(...latitudes)) / 2;
				const centerLng = (Math.min(...longitudes) + Math.max(...longitudes)) / 2;
				
				targetPosition = [centerLat, centerLng];
				break;
		}

		if (targetPosition) {
			// Центрируем карту на выбранной позиции
			map.setView(targetPosition, MAP_OBJECT_ZOOM, {
				animate: true,
			});
		} else {
			// Fallback - просто меняем зум
			map.setZoom(MAP_OBJECT_ZOOM);
		}
	}

	return (
		<MapControlContainer position={["bottom"]}>
			<div
				style={{
					position: "relative",
					bottom: "50px",
					width: "100vw",
					display: "flex",
					justifyContent: "center",
				}}
			>
				<Stack direction="row" gap="19px" alignContent="center" sx={{}}>
					<ButtonGroup
						items={[
							{
								titleKey: "Zoom in",
								onClick: zoomIn,
								Icon: PlusIcon,
								color: "var(--black-400)",
							},
							{
								titleKey: "Zoom out",
								onClick: zoomOut,
								Icon: MinusIcon,
								color: "var(--black-400)",
							},
						]}
					/>

					<Button
						variant="contained"
						sx={{
							backgroundColor: "white",
							border: "1px solid var(--black-300)",
							padding: "15px",
							boxShadow: "5px 5px 10px 0px rgba(0, 0, 0, 0.25)",
							minWidth: "50px",
						}}
						onClick={zoomDefault}
					>
						<img
							src="/images/zoom_navigate.svg"
							alt="Zoom Center"
						/>
					</Button>


				</Stack>
			</div>
		</MapControlContainer>
	);
}
