import React, { useState, useEffect } from 'react';
import { useMapsLibrary } from '@vis.gl/react-google-maps';

export const GeocodeComponent = () => {
  // Use state to store the geocoding results
  const [latLng, setLatLng] = useState<{ lat: number; lng: number } | null>(null);
  const [address, setAddress] = useState<string>('');

  // Use the hook to load the geocoding library
  const geocodingLibrary = useMapsLibrary('geocoding');

  // Create an instance of the Geocoder once the library is loaded
  useEffect(() => {
    if (!geocodingLibrary || !address) {
      return;
    }

    const geocoder = new geocodingLibrary.Geocoder();
    
    // Perform the geocode request
    geocoder.geocode(
      {
        address: address,
      },
      (results, status) => {
        if (status === 'OK' && results) {
          // If a result is found, extract the lat/lng
          const location = results[0].geometry.location;
          setLatLng({ lat: location.lat(), lng: location.lng() });
        } else {
          setLatLng(null);
          console.error('Geocode was not successful for the following reason: ' + status);
        }
      },
    );
  }, [geocodingLibrary, address]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAddress(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Enter a city, state, or zip code"
        value={address}
        onChange={handleInputChange}
      />
      {latLng && (
        <p>
          Latitude: {latLng.lat}, Longitude: {latLng.lng}
        </p>
      )}
      {!latLng && address && <p>No results found.</p>}
    </div>
  );
};