import { LocationOn, Check } from "@mui/icons-material";
import {
	Dialog,
	DialogTitle,
	DialogContent,
	DialogActions,
	Button,
	TextField,
	Stack,
	Alert,
	Box,
} from "@mui/material";
import { LatLng, Icon } from "leaflet";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { MapContainer, TileLayer, Marker, useMapEvents } from "react-leaflet";

import "leaflet/dist/leaflet.css";

// Фиксим проблему с иконками Leaflet
delete (Icon.Default.prototype as any)._getIconUrl;
Icon.Default.mergeOptions({
	iconRetinaUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png",
	iconUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png",
	shadowUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png",
});

interface PositionSelectorProps {
	open: boolean;
	onClose: () => void;
	onPositionSelected: (lat: number, lng: number) => void;
	initialLat?: number;
	initialLng?: number;
}

function MapClickHandler({ onPositionSelected }: { onPositionSelected: (lat: number, lng: number) => void }) {
	const map = useMapEvents({
		click: (e) => {
			const { lat, lng } = e.latlng;
			onPositionSelected(lat, lng);
		},
	});
	return null;
}

export function PositionSelector({ 
	open, 
	onClose, 
	onPositionSelected, 
	initialLat = 52.2833, 
	initialLng = 76.9667 
}: PositionSelectorProps) {
	const { t } = useTranslation();
	const [selectedPosition, setSelectedPosition] = useState<LatLng | null>(null);
	const [manualLat, setManualLat] = useState(initialLat.toString());
	const [manualLng, setManualLng] = useState(initialLng.toString());

	useEffect(() => {
		if (open) {
			setSelectedPosition(new LatLng(initialLat, initialLng));
		}
	}, [open, initialLat, initialLng]);

	const handleMapClick = (lat: number, lng: number) => {
		const position = new LatLng(lat, lng);
		setSelectedPosition(position);
		setManualLat(lat.toFixed(6));
		setManualLng(lng.toFixed(6));
	};

	const handleUseCurrentCenter = () => {
		// Используем текущую позицию как центр
		const lat = parseFloat(manualLat);
		const lng = parseFloat(manualLng);
		if (!isNaN(lat) && !isNaN(lng)) {
			setSelectedPosition(new LatLng(lat, lng));
		}
	};

	const handleConfirm = () => {
		if (selectedPosition) {
			onPositionSelected(selectedPosition.lat, selectedPosition.lng);
			onClose();
		}
	};

	const handleManualInput = () => {
		const lat = parseFloat(manualLat);
		const lng = parseFloat(manualLng);
		if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
			setSelectedPosition(new LatLng(lat, lng));
		}
	};

	return (
		<Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
			<DialogTitle>
				{t("Выберите позицию на карте")}
			</DialogTitle>
			<DialogContent>
				<Stack spacing={2} sx={{ mt: 1 }}>
					<Alert severity="info">
						{t("Кликните на карте, чтобы выбрать позицию, или введите координаты вручную")}
					</Alert>

					<Box sx={{ height: "400px", width: "100%", position: "relative" }}>
						<MapContainer
							center={[initialLat, initialLng]}
							zoom={10}
							scrollWheelZoom={true}
							style={{ height: "100%", width: "100%" }}
							zoomControl={true}
						>
							<TileLayer
								attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
								url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
							/>
							<MapClickHandler onPositionSelected={handleMapClick} />
							{selectedPosition && (
								<Marker position={selectedPosition} />
							)}
						</MapContainer>
					</Box>

					<Stack direction="row" spacing={2}>
						<TextField
							fullWidth
							label={t("Широта")}
							type="number"
							value={manualLat}
							onChange={(e) => setManualLat(e.target.value)}
							onBlur={handleManualInput}
							inputProps={{ step: 0.000001, min: -90, max: 90 }}
							placeholder="52.2833"
						/>
						<TextField
							fullWidth
							label={t("Долгота")}
							type="number"
							value={manualLng}
							onChange={(e) => setManualLng(e.target.value)}
							onBlur={handleManualInput}
							inputProps={{ step: 0.000001, min: -180, max: 180 }}
							placeholder="76.9667"
						/>
					</Stack>

					{selectedPosition && (
						<Alert severity="success" icon={<Check />}>
							{t("Позиция выбрана:")} {selectedPosition.lat.toFixed(6)}, {selectedPosition.lng.toFixed(6)}
						</Alert>
					)}
				</Stack>
			</DialogContent>
			<DialogActions>
				<Button onClick={onClose}>
					{t("Отмена")}
				</Button>
				<Button 
					onClick={handleConfirm} 
					variant="contained" 
					disabled={!selectedPosition}
					startIcon={<LocationOn />}
				>
					{t("Подтвердить позицию")}
				</Button>
			</DialogActions>
		</Dialog>
	);
} 