import React from 'react';
import {observer, inject} from 'mobx-react';
import {AutoComplete} from 'material-ui';
@inject('appstate')
@observer
export default class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      geoaddress : 'RW.10 Menteng Kota Jakarta Pusat'
    }
    this.addressStore = props.appstate.userAddress;
  }


  componentDidMount() {
        const google = window.google;
        this.map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: {
            lat: -6.206491, 
            lng: 106.844651
          },
          disableDefaultUI: true,
          zoomControl : true,
          gestureHandling: 'greedy'
        });

        var defaultBounds = new google.maps.LatLngBounds(
          new google.maps.LatLng(-33.8902,151.1759),
          new google.maps.LatLng(-33.8474,151.2631)
        );


        // Create the search box and link it to the UI element.
        // this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(document.getElementById('pac-input'));
        var marker= new google.maps.Marker({
          map : this.map,
        });

        var geocoder  = new google.maps.Geocoder();

        var input = document.getElementById('pac-input');
        let autocomplete = new google.maps.places.AutocompleteService();

        google.maps.event.addListener(this.map, 'click', function(event) {
           let latLng = {
             lat: event.latLng.lat(),
             lng: event.latLng.lng(),
           };
           
           // this.markers.push(marker);
        marker.setPosition(latLng); 

          geocoder.geocode({ location: latLng }, (results, status) => {
            if (status === 'OK') {
              // this.setState({
                // geoaddress: results[0].formatted_address
              // })
                setAddress(results[0].formatted_address,latLng)
              
            }
          });

        });

        var setAddress = (la,position)=>{
          this.setState({
            geoaddress : la
          })
          this.addressStore.setGeoData({
            geoaddress : la,
            lat : position.lat,
            lng : position.lng
          })
        }

        this.onChooseAddress = (id)=>{
          geocoder.geocode({'placeId': id}, (results, status) => {
              if (status === 'OK') {
                
                this.map.fitBounds(results[0].geometry.viewport);
                this.map.setCenter(results[0].geometry.location);
                
                // if(this.marker) {
                //   this.marker.setMap(null);
                // }

                // console.log(results[0], 'results');
                // console.log(results[0].geometry.location, 'location');
                // console.log(results[0].geometry.location.lat(),results[0].geometry.location.lng(),'location');

                marker.setPosition(results[0].geometry.location);

                this.setState({
                  geoaddress : results[0].formatted_address
                });

                this.addressStore.setGeoData({
                  geoaddress : results[0].formatted_address,
                  lat : results[0].geometry.location.lat(),
                  lng : results[0].geometry.location.lng()
                });

              } else {
                console.log('Geocode was not successful for the following reason: ' + status);
              }
            });
      }

  }

  render() {
    return (
      <div>
      <AutoComplete
        hintText="Search location"
        textFieldStyle={{fontSize: 14, fontWeight: 400}}
        menuStyle={{
          fontSize: 12
        }}
        searchText={this.addressStore.searchValue}
        onNewRequest={(choosenRequest, index) => {
          this.onChooseAddress(choosenRequest.place_id);
          
        }}
        dataSource={this.addressStore.autocompleteData.slice()}
        filter={() => {
          return true;
        }}
        fullWidth={true}
        onUpdateInput={(value) => this.addressStore.searchPlaces(value)}
      />
        <div
        id="map"
        style={{
          display: 'block',
          height: '345px',
          width: "100%",
          marginBottom: 0,
          marginLeft: "auto",
          marginRight: "auto",
          padding: 20
        }}>
        </div>
        <div style={{height:'50px',width:'100%','background' : '#f8f8f8','display' : 'flex','alignItems' : 'center','justifyContent' : 'center',color : '#000',fontSize : '0.8em',padding : '5px'}}>
          {this.state.geoaddress}
        </div>

      </div>
      );
  }
}
