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

import PlacesAutocomplete from 'react-places-autocomplete'

import {
  geocodeByAddress,
  geocodeByPlaceId,
  getLatLng,
} from 'react-places-autocomplete'

export default function LocationSearchInput({ value, onChange, disabled }) {
  const [address, setAddress] = useState(
    value && value.value ? value.value : value,
  )

  const [coordinates, setCoordinates] = useState({ lat: null, lng: null })

  const handleSelect = async (value) => {
    const results = await geocodeByAddress(value)

    const ll = await getLatLng(results[0])

    console.log(ll)

    setAddress(value)

    onChange({ ll, value })

    setCoordinates(ll)

    return ll
  }

  return (
    <div>
      {/* <p><b>Lat:</b> {coordinates.lat}</p>

            <p><b>Lng:</b> {coordinates.lng}</p>

            <p><b>Address:</b> {address}</p> */}

      <PlacesAutocomplete
        value={address}
        onChange={setAddress}
        onSelect={handleSelect}
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div key={suggestions.description} className="input">
            <input
              {...getInputProps({
                placeholder: 'Search Places ...',
                className: 'ant-input',
                disabled: disabled,
              })}
            />
            <div
              className="autocomplete-dropdown-container"
              style={{
                position: 'absolute',
                background: 'white',
                border: ' 1px solid #e2e2e2',
                zIndex: '999',
                width: '100%',
              }}
            >
              {loading && <div>Loading...</div>}
              {suggestions.map((suggestion) => {
                const className = suggestion.active
                  ? 'suggestion-item--active'
                  : 'suggestion-item'
                // inline style for demonstration purpose
                const style = suggestion.active
                  ? {
                      backgroundColor: '#D3D3D3',
                      cursor: 'pointer',
                      padding: '5px',
                    }
                  : {
                      backgroundColor: 'white',
                      cursor: 'pointer',
                      padding: '5px',
                    }
                return (
                  <div
                    {...getSuggestionItemProps(suggestion, {
                      className,
                      style,
                    })}
                  >
                    <span>{suggestion.description}</span>
                  </div>
                )
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
    </div>
  )
}
