import classNames from 'classnames';
import React, { useState } from 'react';
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng,
} from 'react-places-autocomplete';

interface LocationState {
  address: string;
  coordinates: {
    lat: number | null;
    lng: number | null;
  };
}

interface LocationSearchInputProps {
    className?: string;
}

const LocationSearchInput: React.FC<LocationSearchInputProps> = ({className}) => {
  const [location, setLocation] = useState<LocationState>({
    address: '',
    coordinates: { lat: null, lng: null },
  });

  const handleChange = (address: string) => {
    setLocation((prev) => ({ ...prev, address }));
  };

  const handleSelect = async (address: string) => {
    try {
      const results = await geocodeByAddress(address);
      const latLng = await getLatLng(results[0]);
      setLocation({ address, coordinates: latLng });
    } catch (error) {
      console.error('Error selecting place:', error);
    }
  };

  return (
    <div className="w-full">
      <PlacesAutocomplete
        value={location.address}
        onChange={handleChange}
        onSelect={handleSelect}
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div>
            <input
              {...getInputProps({
                placeholder: 'Search by City, Zip Code, or your Full Address...',
                className:  `location-search-input w-full px-2 focus:outline-hidden ${className}`,
              })}
            />
            <div className="autocomplete-dropdown-container">
              {loading && <div>Loading...</div>}
              {suggestions.map((suggestion) => {
                const className = suggestion.active
                  ? 'suggestion-item--active bg-atmosphere cursor-pointer'
                  : 'suggestion-item bg-deepcove cursor-pointer';
                return (
                  <div
                    {...getSuggestionItemProps(suggestion, {
                      className,
                    })}
                  >
                    <span>{suggestion.description}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
      {/* {location.coordinates.lat && location.coordinates.lng && (
        <p>
          Selected Coordinates: Lat: {location.coordinates.lat}, Lng:{' '}
          {location.coordinates.lng}
        </p>
      )} */}
    </div>
  );
};

export default LocationSearchInput;