/* global lgMapData */
import { useState, useEffect, useRef } from '@wordpress/element';
import { ComboboxControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const AddressBox = ({ marker, index, updateMarker }) => {
	const [query, setQuery] = useState(marker.address || '');
	const [selectedItem, setSelectedItem] = useState(marker.place_id || '');
	const [results, setResults] = useState(
		marker.address ? [
			{
				place_id: marker.place_id,
				address: marker.address,
				lat: marker.lat,
				lng: marker.lng
			}] :
			[]
	);
	const [loading, setLoading] = useState(false);
	const [error, setError] = useState('');
	const debounceRef = useRef(null);

	const fetchLatLng = async (address) => {
		if (!address) return;
		try {
			setLoading(true);
			const response = await fetch(
				`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
					address
				)}&key=${window.atob(lgMapData.gak)}`
			);
			const data = await response.json();
			if (data.status === 'OK') {
				const options = data.results.map((res) => ({
					place_id: res.place_id,
					address: res.formatted_address,
					lat: res.geometry.location.lat.toString(),
					lng: res.geometry.location.lng.toString(),
				}));
				setResults(options);
				setError('');
			} else {
				setResults([]);
				setError(__('Location not found', 'lead-gen'));
			}
		} catch (e) {
			setResults([]);
			setError(__('Error fetching location', 'lead-gen'));
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		if (!query) {
			setResults([]);
			setError('');
			return;
		}

		if (debounceRef.current) clearTimeout(debounceRef.current);

		debounceRef.current = setTimeout(() => {
			fetchLatLng(query);
		}, 500);

		return () => clearTimeout(debounceRef.current);
	}, [query]);

	const handleSelect = (val) => {
		if (!val) return;
		const selectedOption = results.find(item => item.place_id === val);

		if (selectedOption) {
			updateMarker( index, null, selectedOption);
			setSelectedItem(val);
		}
	};

	const onFilterValueChange = (val) => {
		setQuery(val);
	}

	return (
		<div className="address-box">
			<ComboboxControl
				label={__('Address', 'lead-gen')}
				value={selectedItem || query || ''}
				options={results.map(item => ({label: item.address, value: item.place_id}))}
				onChange={handleSelect}
				onFilterValueChange={onFilterValueChange}
			/>
			{loading && <p>{__('Searching…', 'lead-gen')}</p>}
			{error && <p style={{ color: 'red' }}>{error}</p>}
		</div>
	);
};

export default AddressBox;
