/* global google */
import { useEffect, useRef } from '@wordpress/element';

const MiniMap = ({ lat, lng, onChange }) => {
	const mapRef = useRef(null);
	const markerRef = useRef(null);
	const mapInstance = useRef(null);

	useEffect(() => {
		if (!window.google?.maps || (!lat && !lng)) return;

		const position = {
			lat: parseFloat(lat) || 0,
			lng: parseFloat(lng) || 0,
		};

		if (!mapInstance.current) {
			mapInstance.current = new google.maps.Map(mapRef.current, {
				center: position,
				zoom: 16,
			});

			markerRef.current = new google.maps.Marker({
				position,
				map: mapInstance.current,
				draggable: true,
			});

			mapInstance.current.addListener('click', (e) => {
				const newPos = { lat: e.latLng.lat(), lng: e.latLng.lng() };
				markerRef.current.setPosition(newPos);
				if (onChange) {
					onChange(newPos);
				}
			});

			markerRef.current.addListener('dragend', (e) => {
				const newPos = { lat: e.latLng.lat(), lng: e.latLng.lng() };
				if (onChange) {
					onChange(newPos);
				}
			});
		} else {
			mapInstance.current.setCenter(position);
			markerRef.current.setPosition(position);
		}
	}, [lat, lng, onChange]);

	return (
		<div
			ref={mapRef}
			style={{
				width: '100%',
				height: '200px',
				borderRadius: '6px',
				marginTop: '10px',
				marginBottom: '10px',
			}}
		/>
	);
};

export default MiniMap;
