import React, { useEffect, useRef, useState } from 'react';

const GOOGLE_MAPS_API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;

const SimpleAutocomplete = () => {
  const inputRef = useRef(null);
  const autocompleteRef = useRef(null);

  useEffect(() => {
    const loadScript = (url, callback) => {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src = url;
      script.onload = callback;
      document.head.appendChild(script);
    };

    if (!window.google) {
      loadScript(`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=places`, () => {
        initAutocomplete();
      });
    } else {
      initAutocomplete();
    }

    function initAutocomplete() {
      if (!inputRef.current) return;

      autocompleteRef.current = new window.google.maps.places.Autocomplete(inputRef.current, {
        types: ['geocode'],
        componentRestrictions: { country: 'in' } // optional
      });

      autocompleteRef.current.addListener('place_changed', () => {
        const place = autocompleteRef.current.getPlace();
        console.log('Selected Place:', place);
      });
    }
  }, []);

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Start typing address" style={{ width: '100%', padding: '10px', fontSize: '16px' }} />
    </div>
  );
};

export default SimpleAutocomplete;
