import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import Link from 'react-router';
import ActionHome from 'material-ui/svg-icons/action/home';
import ActionWork from 'material-ui/svg-icons/action/work';
import MapsMyLocation from 'material-ui/svg-icons/maps/my-location';
import MapsAddLocation from 'material-ui/svg-icons/maps/add-location';
import MapsNearMe from 'material-ui/svg-icons/maps/near-me';
import MapsLocalHospital from 'material-ui/svg-icons/maps/local-hospital';
import MapsLocalPharmacy from 'material-ui/svg-icons/maps/local-pharmacy';
import AutoComplete from 'material-ui/AutoComplete';
import { fullWhite } from 'material-ui/styles/colors';
import Dialog from 'material-ui/Dialog';
import { List, ListItem, makeSelectable } from 'material-ui/List';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import $ from 'jquery';
import GeolocationService from './Geolocation';
import Instance from '../../../components/Connection';

let SelectableList = makeSelectable(List);

function wrapState(ComposedComponent) {
  return class SelectableList extends Component {
    static propTypes = {
      children: PropTypes.node.isRequired,
      defaultValue: PropTypes.number.isRequired,
    };

    componentWillMount() {
      this.setState({
        selectedIndex: this.props.defaultValue,
      });
    }

    handleRequestChange = (event, index) => {
      this.setState({
        selectedIndex: index,
      });
    };

    render() {
      return (
        <ComposedComponent
          value={this.state.selectedIndex}
          onChange={this.handleRequestChange}
        >
          {this.props.children}
        </ComposedComponent>
      );
    }
  };
}

SelectableList = wrapState(SelectableList);

const customContentStyle = {
  width: '100%',
  maxWidth: '600px',
};

const buttonStyle = {

};

const buttonStyleWhite = {
  textAlign: 'left',
  textTransform: 'none !important',
  padding: '0px 0px 0px 0px',
  marginTop: 0,
  boxShadow: 'none',
  color: 'rgba(0, 0, 0, 0.3)',
  display: 'inline'
};


const datasourceConfig = { text: 'providerText', value: 'muk_id' }
const service = new google.maps.places.AutocompleteService();
const placeService = new google.maps.places.PlacesService(document.createElement('div'));
const autoComplete = new google.maps.places.AutocompleteService();

export class NEMTLocation extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      data: {
        "id": "",
        "origin": {
          "name": "",
          "lat": 0,
          "lng": 0,
          "address": ""
        },
        "destination": {
          "name": "",
          "lat": 0,
          "lng": 0,
          "address": ""
        }
      },
      open: false,
      nearbyPlaces: [],
      textSize: '16',
      icon: '',
      type: '',
      buttonValue: '',
      locationType: '',
      geolocation: {
        lat: 0,
        long: 0
      },
      providers: [],
      currentSelection: {
        id: 0,
        name: "",
        address: "",
        lat: "",
        lng: "",
        type: "",
        saved: false,
      },
      inputValue: "",
      addLocation: false,
      searchAddresses: [],
      addLocationText: '',
      addLocationTextValue: '',
      addLocationType: 'custom',
      addLocationSelected: {},
      addLocationCustomLabel: '',
      addLocationID: '',
      user: {
        useruuid: '',
        addresses: []
      },
      currentLocation: null,
      currentLocationBaseName: 'Current Location',
      address: {
        id: '',
        name: '',
        address: '',
      }
    }

    this.addCustomLabel = this.addCustomLabel.bind(this);
    this.geoSuccess = this.geoSuccess.bind(this);
    this.handleAddAddress = this.handleAddAddress.bind(this);
    this.handleAutocomplete = this.handleAutocomplete.bind(this);
    this.handleBack = this.handleBack.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleOpen = this.handleOpen.bind(this);
    this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
    this.handleSave = this.handleSave.bind(this);
    this.handleSaveAddress = this.handleSaveAddress.bind(this);
    this.locateNearby = this.locateNearby.bind(this);
    this.noPosition = this.noPosition.bind(this);
    this.updateTextSearch = this.updateTextSearch.bind(this);
    this.handleCurrentLocation = this.handleCurrentLocation.bind(this);
    this.updateLocation = this.updateLocation.bind(this);
    this.handleGetClosestPlace = this.handleGetClosestPlace.bind(this);

    // this.updateLocation().then(console.log);


    this.updateLocation();
  }

  static propTypes = {
    data: React.PropTypes.object.isRequired,
    title: React.PropTypes.string,
    value: React.PropTypes.string,
    buttonvalue: React.PropTypes.string,
    onPlaceChanged: React.PropTypes.function,
    icon: React.PropTypes.string,
    textSize: React.PropTypes.integer,
    type: React.PropTypes.string,
    locationType: React.PropTypes.string,
    address: React.PropTypes.object
  }

  geoSuccess = (position) => {

    const geo = GeolocationService.GetCoordinates();
    // self.updateLocation().then(p => {
    let lat = geo.lat;
    let long = geo.long;

    this.locateNearby(lat, long)
  }

  locateNearby = (lat, long) => {
    if (lat === 0 || long === 0) {
      lat = 41.886406;
      long = -87.624225;
    }
    if (this.state.locationType === 'provider') {
      Instance.getRawConn().get(`/v1/nemt/provider/participating?sort=distance&lat=${lat}&long=${long}`).then(res => {
        let nearByPlaces = [];
        let providers = res.data.map(p => {
          if (p.address.street_address_1) {
            const streetNumber = p.address.street_address_1.split(' ')[0]
            let clickResult = {
              id: p.muk_id,
              address: `${p.address.street_address_1}, ${p.address.city}, ${p.address.state} (${p.address.zipcode})`,
              lat: p.address.lat,
              lng: p.address.long,
              name: p.name,
              type: "provider",
              raw: p,
              street_number: streetNumber,
              street: p.address.street_address_1.replace(streetNumber, '').trim(),
              city: p.address.city,
              state: p.address.state,
              zipcode: p.address.zipcode.substring(0, 5),
              country: p.address.country,
              saved: false,
            }
            clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`

            var listItem = (<ListItem primaryText={p.name} secondaryText={clickResult.address} key={p.muk_id} rightIcon={<MapsLocalHospital />} onClick={(event) => this.handlePlaceChanged(clickResult)} />)
            nearByPlaces.push(listItem);
            p.providerText = `${p.name} - ${p.address.street_address_1}, ${p.address.city}, ${p.address.state} (${p.address.zipcode}) (${p.address.phone_number})`
          }
          return p;
        });

        this.setState(Object.assign(this.state, { nearbyPlaces: nearByPlaces, providers: providers }));
      });
    } else {
      var pyrmont = new google.maps.LatLng(lat, long);
      var request = {
        location: pyrmont,
        radius: '500'
      };
      placeService.nearbySearch(request, this.callbackGeoSuccess);
    }
  }

  setFullAddress = (name) => {
    name.raw.address_components.forEach(a => {
      a.types.forEach(c => {
        switch (c) {
          case "street_number":
            name.street_number = a.short_name;
            break;
          case "route":
            name.street = a.short_name;
            break;
          case "locality":
            name.city = a.short_name;
            break;
          case "administrative_area_level_1":
            name.state = a.short_name;
            break;
          case "country":
            name.country = a.short_name;
            break;
          case "postal_code":
            name.zipcode = a.short_name;
            break;
        }
      }, this)
    }, this);
    name.address = `${name.street_number} ${name.street}, ${name.city}`

    return name
  }

  handlePlaceChanged = (name) => {
    var self = this;
    const getFullObject = () => {
      return new Promise((resolve, reject) => {
        if (name.type !== 'google' && name.type !== 'provider') {
          resolve(name);
        }

        if (self.state.locationType === 'provider') {
          resolve(name);
        } else {
          if (name.raw && name.raw.address_components) {
            name = self.setFullAddress(name);
            resolve(name)
          } else {
            placeService.getDetails(name, (result, status) => {
              if (status == google.maps.places.PlacesServiceStatus.OK) {
                name.raw = result
                name = self.setFullAddress(name);
                resolve(name);
              } else {
                reject(result);
              }
            });
          }
        }
      });
    }

    getFullObject().then(name => {
      self.setState(Object.assign(self.state, { currentSelection: name }));

      if (self.props.onPlaceChanged) {
        self.props.onPlaceChanged(name);
      }

      self.locateNearby(name.lat, name.lng);

      let buttonText = name.name;
      if (buttonText.length > self.state.textSize) {
        buttonText = buttonText.substring(0, self.state.textSize);
        buttonText += '...';
      }
      self.setState(Object.assign(self.state, { buttonValue: buttonText, inputValue: name.address }));
    }).catch(console.error);
  }

  callbackGeoSuccess = (results, status) => {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var nearByPlaces = [];
      for (var i = 0; i < 5; i++) {
        var place = results[i];
        if (place) {
          let clickResult = {
            id: place.id,
            placeId: place.place_id,
            address: place.formatted_address ? place.formatted_address : (place.vicinity ? place.vicinity : place.name),
            lat: place.geometry.location.lat(),
            lng: place.geometry.location.lng(),
            name: place.name,
            type: "google",
            raw: place,
            saved: false,
          }
          var listItem = (<ListItem primaryText={place.name} secondaryText={clickResult.address} key={place.name} rightIcon={<MapsLocalHospital />} onClick={(event) => this.handlePlaceChanged(clickResult)} />)
          nearByPlaces.push(listItem);
        }
      }
      this.setState(Object.assign(this.state, { nearbyPlaces: nearByPlaces }));
    }
  }

  componentDidMount = () => {
    const self = this;
    var objConf = {
      data: this.props.data,
      open: false,
      buttonValue: this.props.buttonvalue,
      icon: this.props.icon,
      textSize: this.props.textSize,
      type: this.props.type,
      locationType: this.props.locationType,
      addLocation: false,
      currentLocation: (<ListItem primaryText={this.state.currentLocationBaseName} leftIcon={<MapsNearMe />} onTouchTap={this.handleGetClosestPlace} />),
      address: this.props.address
    }

    if (this.props.locationType == 'provider') {
      objConf.currentLocationBaseName = "Nearest Provider"
      objConf.currentLocation = (<ListItem primaryText={objConf.currentLocationBaseName} leftIcon={<MapsNearMe />} onTouchTap={this.handleGetClosestPlace} />)
    }

    if (!objConf.buttonValue || objConf.buttonValue === null) objConf.buttonValue = '';

    if (objConf.textSize <= '0') {
      objConf.textSize = '20';
    }

    if (objConf.address && objConf.address.id !== '' && objConf.address.name !== '') {
      objConf.currentSelection = objConf.address
      objConf.buttonValue = objConf.address.name
      objConf.inputValue = objConf.address.name
    }

    if (!objConf.buttonValue) {
      objConf.buttonValue = this.props.buttonvalue;
    }

    if (objConf.buttonValue && objConf.buttonValue.length > objConf.textSize) {
      objConf.buttonValue = objConf.buttonValue.substring(0, objConf.textSize);
      objConf.buttonValue += '...';
    }

    // if (self.state.user.useruuid === '') {
    //   if (objConf.data.user && objConf.data.user !== null && objConf.data.user.useruuid !== '') {
    //     let url = `/v1/nemt/users/member/` + objConf.data.user.useruuid
    //     instance.get(url).then(res => {
    //       let user = res.data;
    //       self.setState(Object.assign(self.state, { user: user }));
    //     }).catch(console.error);
    //   }
    // }

    this.setState(Object.assign(this.state, objConf));

    if (this.state.type === "flat") {
      let dt = $(ReactDOM.findDOMNode(this)).find('#' + this.state.data.id);
    }
  }

  componentWillReceiveProps = (nextProps) => {
    const self = this;
    var objConf = {
      data: nextProps.data,
      buttonValue: nextProps.buttonvalue,
      icon: nextProps.icon,
      textSize: nextProps.textSize,
      type: nextProps.type,
      locationType: nextProps.locationType,
      addLocation: false,
      currentLocation: (<ListItem primaryText={this.state.currentLocationBaseName} leftIcon={<MapsNearMe />} onTouchTap={this.handleGetClosestPlace} />),
      address: nextProps.address
    }

    if (!objConf.buttonValue || objConf.buttonValue === null) objConf.buttonValue = '';

    if (objConf.textSize <= 0) {
      objConf.textSize = 20;
    }

    if (objConf.address && objConf.address.id !== '' && objConf.address.name !== '') {
      objConf.currentSelection = objConf.address
      objConf.buttonValue = objConf.address.name
      objConf.inputValue = objConf.address.name
    }

    if (!objConf.buttonValue) {
      objConf.buttonValue = nextProps.buttonvalue;
    }

    if (objConf.buttonValue && objConf.buttonValue.length > objConf.textSize) {
      objConf.buttonValue = objConf.buttonValue.substring(0, objConf.textSize);
      objConf.buttonValue += '...';
    }

    // if (self.state.user.useruuid === '' || self.state.user.useruuid !== objConf.data.user.useruuid) {
    //   if (objConf.data.user && objConf.data.user !== null && objConf.data.user.useruuid !== '') {
    //     let url = `/v1/nemt/users/member/` + objConf.data.user.useruuid
    //     instance.get(url).then(res => {
    //       let user = res.data;
    //       self.setState(Object.assign(self.state, { user: user }));
    //     }).catch(console.error);
    //   }
    // }

    this.setState(Object.assign(this.state, objConf));

    let $this = $(ReactDOM.findDOMNode(this));
    const state = this

    if (this.state.type === "flat") {
      let dt = $(ReactDOM.findDOMNode(this)).find('#' + this.state.data.id);
    }
  }

  handleOpen = (e) => {
    if (!this.state.address || !this.state.address.id) {
      this.handleCurrentLocation(e);
    }

    this.setState(Object.assign(this.state, { open: true }));
    if (this.state.user.useruuid === '' || this.state.user.useruuid !== this.props.data.user.useruuid) {
      if (this.props.data.user && this.props.data.user.useruuid !== undefined && this.props.data.user !== null && this.props.data.user.useruuid !== '') {
        let url = `/v1/nemt/users/member/` + this.props.data.user.useruuid
        Instance.getRawConn().get(url).then(res => {
          let user = res.data;
          this.setState(Object.assign(this.state, { user: user }));
        }).catch(console.error);
      }
    }
  };

  handleCancel = () => {
    this.setState(Object.assign(this.state, { open: false }));
  };

  handleClose = () => {
    if (this.props.onPlaceChanged) {
      this.props.onPlaceChanged(this.state.currentSelection);
    }

    let buttonText = this.state.currentSelection.name;
    if (buttonText.length > this.state.textSize) {
      buttonText = buttonText.substring(0, this.state.textSize);
      buttonText += '...';
    }

    this.setState(Object.assign(this.state, { open: false, buttonValue: buttonText }));
  };

  noPosition = () => {
    this.locateNearby(41.886406, -87.624225);
  }

  updateTextSearch(searchText, dtSource, params) {
    let self = this;
    self.setState(Object.assign(self.state, { inputValue: searchText }));
    if (searchText.length >= 3) {
      let lat = self.state.geolocation.lat;
      let long = self.state.geolocation.long;
      if (lat === 0 || long === 0) {
        lat = 41.886406;
        long = -87.624225;
      }

      if (self.state.locationType === 'provider') {
        //let url = `/v1/nemt/provider?lat=${lat}&long=${long}&limit=20&name=${searchText}&sortby=distance`
        let url = `/v1/nemt/provider/participating?lat=${lat}&long=${long}&query=${searchText}&sortby=distance`
        Instance.getRawConn().get(encodeURI(url)).then(res => {
          if (res.data.length > 0) {
            let places = res.data.map(p => {
              p.providerText = `${p.name} - ${p.address.street_address_1}, ${p.address.city}, ${p.address.state} (${p.address.zipcode}) (${p.address.phone_number})`
              p.saved = false
              return p;
            })
            self.setState(Object.assign(self.state, { providers: places }));
            dtSource = self.state.providers;
          }
        });
      } else {
        var location = new google.maps.LatLng(lat, long);
        var request = {
          location: location,
          radius: '500',
          input: searchText,
          componentRestrictions: { country: 'us' },
        };
        const callback = (results, status) => {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            var googlePlaces = results.map(place => {
              place.providerText = place.description;
              place.muk_id = place.id;
              place.saved = false;
              return place;
            });
            self.setState(Object.assign(self.state, { providers: googlePlaces }));
          }
        }

        service.getPlacePredictions(request, callback);
      }
    }
  }

  addCustomLabel(e) {
    this.setState(Object.assign(this.state, { addLocationCustomLabel: e.target.value }));
  }

  searchAddress(e) {
    let providerSearch = e.target.value;
    this.setState(Object.assign(this.state, { addLocationTextValue: providerSearch }));
    if (providerSearch.length >= 3) {

      const geo = GeolocationService.GetCoordinates();
      let lat = geo.lat;
      let long = geo.long;
      if (lat === 0 || long === 0) {
        lat = 41.886406;
        long = -87.624225;
      }
      if (this.state.locationType === 'provider') {
        let url = `/v1/nemt/provider/participating?lat=${lat}&long=${long}&query=${providerSearch}&sortby=distance`
        Instance.getRawConn().get(encodeURI(url)).then(res => {
          let places = res.data.map(p => {
            const streetNumber = p.address.street_address_1.split(' ')[0]
            p.providerText = `${p.name} - ${p.address.street_address_1}, ${p.address.city}, ${p.address.state} (${p.address.zipcode}) (${p.address.phone_number})`
            let clickResult = {
              id: p.muk_id,
              address: `${p.address.street_address_1}, ${p.address.city}, ${p.address.state} (${p.address.zipcode})`,
              lat: p.address.lat,
              lng: p.address.long,
              name: p.name,
              type: "provider",
              raw: p,
              street_number: streetNumber,
              street: p.address.street_address_1.replace(streetNumber, '').trim(),
              city: p.address.city,
              state: p.address.state,
              zipcode: p.address.zipcode.substring(0, 5),
              country: p.address.country,
              saved: false,
            }
            clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`

            var listItem = (<ListItem value={p.muk_id} primaryText={p.name} secondaryText={clickResult.address} key={p.muk_id} rightIcon={<MapsLocalHospital />} onClick={(event) => this.handleSaveAddress(clickResult, this)} />)
            return listItem;
          });

          this.setState(Object.assign(this.state, { searchAddresses: places }));
        });
      } else {
        var location = new google.maps.LatLng(lat, long);

        let autoComplenteRequest = {
          location: location,
          input: providerSearch,
          radius: '500',
          types: ['address', 'geocode'],
          componentRestrictions: { country: 'us' }
        };

        autoComplete.getQueryPredictions(autoComplenteRequest, (results, status) => {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            var googlePlaces = results.map(place => {
              place.text = place.structured_formatting.main_text;
              let clickResult = {
                id: place.id,
                address: place.description,
                placeId: place.place_id,
                name: place.structured_formatting.main_text,
                type: "google",
                raw: place,
                street_number: '',
                street: '',
                city: '',
                state: '',
                zipcode: '',
                country: '',
                saved: false,
              }

              if (place.address_components) {
                place.address_components.forEach(a => {
                  a.types.forEach(c => {
                    switch (c) {
                      case "street_number":
                        clickResult.street_number = a.short_name;
                        break;
                      case "route":
                        clickResult.street = a.short_name;
                        break;
                      case "locality":
                        clickResult.city = a.short_name;
                        break;
                      case "administrative_area_level_1":
                        clickResult.state = a.short_name;
                        break;
                      case "country":
                        clickResult.country = a.short_name;
                        break;
                      case "postal_code":
                        clickResult.zipcode = a.short_name;
                        break;
                    }
                  }, this)
                }, this);
              }
              //clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}, ${clickResult.state} ${clickResult.zipcode}`

              var listItem = (<ListItem value={clickResult.id} primaryText={clickResult.name} secondaryText={clickResult.address} key={clickResult.id} rightIcon={<MapsLocalHospital />} onClick={(event) => this.handleSaveAddress(clickResult, this)} />)
              return listItem
            });
            this.setState(Object.assign(this.state, { searchAddresses: googlePlaces }));
          }
        });
      }
    }
  }

  handleSaveAddress = (address, state) => {
    if (this.state.locationType === 'provider') {
      state.setState(Object.assign(state.state, { addLocationSelected: address, addLocationTextValue: address.name, addLocationID: address.id }));
    } else {
      placeService.getDetails(address, (result, status) => {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          let clickResult = {
            id: result.place_id,
            placeId: result.place_id,
            address: result.formatted_address ? result.formatted_address : result.vicinity,
            lat: result.geometry.location.lat(),
            lng: result.geometry.location.lng(),
            name: result.name,
            type: "google",
            raw: result,
            street_number: '',
            street: '',
            city: '',
            state: '',
            zipcode: '',
            country: '',
            saved: false,
          }

          result.address_components.forEach(a => {
            a.types.forEach(c => {
              switch (c) {
                case "street_number":
                  clickResult.street_number = a.short_name;
                  break;
                case "route":
                  clickResult.street = a.short_name;
                  break;
                case "locality":
                  clickResult.city = a.short_name;
                  break;
                case "administrative_area_level_1":
                  clickResult.state = a.short_name;
                  break;
                case "country":
                  clickResult.country = a.short_name;
                  break;
                case "postal_code":
                  clickResult.zipcode = a.short_name;
                  break;
              }
            }, this)
          }, this);
          clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`

          state.setState(Object.assign(state.state, { addLocationSelected: clickResult, addLocationTextValue: clickResult.name, addLocationID: clickResult.id }));
        }
      });
    }
  }

  handleAutocomplete = (provider) => {
    const sendInfo = (clickResult) => {
      this.setState(Object.assign(this.state, { currentSelection: clickResult }));
      this.locateNearby(clickResult.lat, clickResult.lng);

      if (this.props.onPlaceChanged) {
        this.props.onPlaceChanged(clickResult);
      }
      //state.handleClose();

      let buttonText = clickResult.name;
      if (buttonText.length > this.state.textSize) {
        buttonText = buttonText.substring(0, this.state.textSize);
        buttonText += '...';
      }
      this.setState(Object.assign(this.state, { buttonValue: buttonText, inputValue: clickResult.name }));
    }

    if (this.state.locationType === "provider") {
      const streetNumber = provider.address.street_address_1.split(' ')[0]
      let clickResult = {
        id: provider.muk_id,
        address: `${provider.address.street_address_1}, ${provider.address.city}, ${provider.address.state} (${provider.address.zipcode})`,
        lat: provider.address.lat,
        lng: provider.address.long,
        name: provider.name,
        type: "provider",
        raw: provider,
        street_number: streetNumber,
        street: provider.address.street_address_1.replace(streetNumber, '').trim(),
        city: provider.address.city,
        state: provider.address.state,
        zipcode: provider.address.zipcode.substring(0, 5),
        country: provider.address.country,
        saved: false,
      }
      clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`

      sendInfo(clickResult);
    } else {
      placeService.getDetails(provider, (result, status) => {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          let clickResult = {
            id: result.place_id,
            placeId: result.place_id,
            address: result.formatted_address ? result.formatted_address : result.vicinity,
            lat: result.geometry.location.lat(),
            lng: result.geometry.location.lng(),
            name: result.name,
            type: "google",
            raw: result,
            street_number: '',
            street: '',
            city: '',
            state: '',
            zipcode: '',
            country: '',
            saved: false,
          }

          result.address_components.forEach(a => {
            a.types.forEach(c => {
              switch (c) {
                case "street_number":
                  clickResult.street_number = a.short_name;
                  break;
                case "route":
                  clickResult.street = a.short_name;
                  break;
                case "locality":
                  clickResult.city = a.short_name;
                  break;
                case "administrative_area_level_1":
                  clickResult.state = a.short_name;
                  break;
                case "country":
                  clickResult.country = a.short_name;
                  break;
                case "postal_code":
                  clickResult.zipcode = a.short_name;
                  break;
              }
            }, this)
          }, this);
          clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`
          sendInfo(clickResult);
        }
      });
    }

  }

  filterResults(searchText, key) {
    if (searchText && key) {
      return (key.toLowerCase().indexOf(searchText.toLowerCase()) !== -1)
    } else return false;
  }

  updateLocation() {
    return new Promise((resolve, reject) => {
      try {
        const geo = GeolocationService.GetCoordinates();
        const position = {
          coords: {
            latitude: geo.lat,
            longitude: geo.long,
          },
        }

        this.geoSuccess(position);
        resolve(position);
      } catch (err) {
        reject(err);
      }
    });
  }

  handleGetClosestPlace(e) {
    const self = this;
    self.updateLocation().then(p => {
      self.handleCurrentLocation(e);
    }).catch(console.error);
  }

  handleCurrentLocation(e) {
    const self = this;
    const geo = GeolocationService.GetCoordinates();
    // self.updateLocation().then(p => {
    let lat = geo.lat;
    let long = geo.long;
    if (lat === 0 || long === 0) {
      lat = 41.886406;
      long = -87.624225;
    }

    if (self.state.locationType === 'provider') {
      Instance.getRawConn().get(`/v1/nemt/provider/participating?sort=distance&lat=${lat}&long=${long}`).then(res => {
        let listItem = (<ListItem primaryText="No location found" key="-1" leftIcon={<MapsNearMe />} onClick={self.handleCurrentLocation} />)
        if (res.data.length > 0) {
          const result = res.data[0];
          const streetNumber = result.address.street_address_1.split(' ')[0]
          let clickResult = {
            id: result.muk_id,
            address: `${result.address.street_address_1}, ${result.address.city}, ${result.address.state} (${result.address.zipcode})`,
            lat: result.address.lat,
            lng: result.address.long,
            name: result.name,
            type: "provider",
            raw: result,
            street_number: streetNumber,
            street: result.address.street_address_1.replace(streetNumber, '').trim(),
            city: result.address.city,
            state: result.address.state,
            zipcode: result.address.zipcode.substring(0, 5),
            country: result.address.country,
            saved: false,
          }
          clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`
          self.handlePlaceChanged(clickResult)
          //listItem = (<ListItem primaryText={clickResult.name} secondaryText={clickResult.address} key={clickResult.muk_id} leftIcon={<MapsNearMe />} onClick={(event) => self.handlePlaceChanged(clickResult)} />)
        }
        //self.setState(Object.assign(self.state, { currentLocation: listItem }));
      }).catch(console.error);
    } else {
      var location = new google.maps.LatLng(lat, long);
      var geocoder = new google.maps.Geocoder;
      var request = {
        location: location,
      };

      const callback = (results, status) => {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          let listItem = (<ListItem primaryText="No location found" key="-1" leftIcon={<MapsNearMe />} onClick={self.handleCurrentLocation} />)
          if (results.length > 0) {
            const result = results[0];
            let clickResult = {
              placeId: result.place_id,
              id: result.id,
              address: result.formatted_address ? result.formatted_address : result.vicinity,
              lat: result.geometry.location.lat(),
              lng: result.geometry.location.lng(),
              name: result.formatted_address ? result.formatted_address : result.vicinity,
              type: "google",
              raw: result,
              street_number: '',
              street: '',
              city: '',
              state: '',
              zipcode: '',
              country: '',
              saved: false,
            }

            result.address_components.forEach(a => {
              a.types.forEach(c => {
                switch (c) {
                  case "street_number":
                    clickResult.street_number = a.short_name;
                    break;
                  case "route":
                    clickResult.street = a.short_name;
                    break;
                  case "locality":
                    clickResult.city = a.short_name;
                    break;
                  case "administrative_area_level_1":
                    clickResult.state = a.short_name;
                    break;
                  case "country":
                    clickResult.country = a.short_name;
                    break;
                  case "postal_code":
                    clickResult.zipcode = a.short_name;
                    break;
                }
              }, this)
            }, this);
            clickResult.address = `${clickResult.street_number} ${clickResult.street}, ${clickResult.city}`
            self.handlePlaceChanged(clickResult);
            //listItem = (<ListItem value={clickResult.id} primaryText={clickResult.address} secondaryText={clickResult.address} key={clickResult.id} leftIcon={<MapsNearMe />} onClick={(event) => self.handlePlaceChanged(clickResult)} />)
          }
          //self.setState(Object.assign(self.state, { currentLocation: listItem }));
        }
      }

      geocoder.geocode(request, callback);
    }
    // }).catch(console.error);
  }

  handleAddAddress = (e, name) => {
    e.preventDefault();
    let text = '';
    switch (name) {
      case 'pcp':
        text = "Enter Member's PCP";
        break;
      case 'custom':
        text = 'Enter Custom Location';
        break;
      case 'home':
        text = "Enter Member's Home Address";
        break;
      case 'work':
        text = "Enter Member's Work Address";
        break;
      default:
        text = 'Enter Custom Address type for Member';
        break;
    }
    this.setState(Object.assign(this.state, {
      addLocation: true,
      addLocationText: text,
      searchAddresses: [],
      addLocationType: name,
      addLocationSelected: {},
      addLocationTextValue: '',
      addLocationID: '',
    }));
  }

  handleBack = () => {
    this.setState(Object.assign(this.state, { addLocation: false, addLocationSelected: {} }));
  }

  handleSave = () => {
    let self = this;
    let address = this.state.addLocationSelected;
    address.address_type = this.state.addLocationType;
    address.user = this.state.data.user;
    address.address = `${address.street_number} ${address.street}, ${address.city}`

    if (this.state.addLocationCustomLabel !== '' && this.state.addLocationCustomLabel !== null && this.state.addLocationCustomLabel !== undefined) {
      address.name = this.state.addLocationCustomLabel;
    }

    if (address.user && address.user !== null) {
      let url = `/v1/nemt/users/member/${address.user.useruuid}/address`
      Instance.getRawConn().post(url, address).then(res => {
        this.setState(Object.assign(this.state, { addLocation: false, addLocationSelected: {}, user: res.data.user, addLocationCustomLabel: '' }));
      }).catch(console.error);
    }
  }

  render() {
    const state = this;
    let actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleCancel}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        keyboardFocused={true}
        onClick={this.handleClose}
      />,
    ];


    let button = (
      <RaisedButton
        label={this.state.buttonValue}
        onClick={this.handleOpen}
        style={buttonStyleWhite}
        labelStyle={buttonStyleWhite}
        buttonStyle={buttonStyleWhite}
        icon={this.state.icon}
        fullWidth={true}
      />);

    if (this.state.type === 'secondary') {
      button = (
        <RaisedButton
          label={this.state.buttonValue}
          onClick={this.handleOpen}
          secondary
          style={buttonStyle}
          icon={this.state.icon}
          fullWidth={true}
        />);
    } else if (this.state.type === 'primary') {
      button = (
        <RaisedButton
          label={this.state.buttonValue}
          onClick={this.handleOpen}
          primary
          style={buttonStyle}
          icon={this.state.icon}
          fullWidth={true}
        />);
    } else if (this.state.type === 'flat') {
      button = (

        <TextField
          id="text-field-controlled"
          // hintText={this.state.buttonValue}
          // floatingLabelText={this.state.buttonValue}
          value={this.state.buttonValue}
          style={{ height: '30px', width: '130px', fontSize: '12px' }}
          onClick={(e) => this.handleOpen(e)} id={this.state.data.id}
        />

        // <a href={"/#/app/table/rides"} onClick={(e) => this.handleOpen(e)} id={this.state.data.id} className={`linkButton ${this.state.data.id}`} >{this.state.buttonValue}</a>
      )
    }
    let customListStyle = {
      overflowScrolling: 'touch',
      WebkitOverflowScrolling: 'touch',
    }

    let homeAddress = (<ListItem primaryText="Add Home" rightIcon={<ArrowDropRight />} leftIcon={<ActionHome />} onClick={(e) => this.handleAddAddress(e, 'home')} />)
    let workAddress = (<ListItem primaryText="Add Work" rightIcon={<ArrowDropRight />} leftIcon={<ActionWork />} onClick={(e) => this.handleAddAddress(e, 'work')} />)
    let customPlaceAddresses = [];
    let pcpAddress = (<ListItem primaryText="Add PCP" rightIcon={<ArrowDropRight />} leftIcon={<ActionHome />} onClick={(e) => this.handleAddAddress(e, 'pcp')} />);
    let customAddresses = [];

    if (this.state.user && this.state.user !== null && this.state.user.addresses && this.state.user.addresses !== null) {
      this.state.user.addresses.forEach(a => {
        let clickResult = {
          id: a.address_uuid,
          address: a.address,
          lat: a.lat,
          lng: a.lng,
          name: a.name,
          type: a.address_type,
          saved: true,
        }

        switch (a.address_type) {
          case 'home':
            clickResult.name = a.address_type_name;
            homeAddress = (<ListItem primaryText={"HOME: " + a.name} secondaryText={clickResult.address} key={a.id} leftIcon={<ActionHome />} onClick={(event) => this.handlePlaceChanged(clickResult)} />);
            break;
          case 'work':
            clickResult.name = a.address_type_name;
            workAddress = (<ListItem primaryText={"WORK: " + a.name} secondaryText={clickResult.address} key={a.id} leftIcon={<ActionWork />} onClick={(event) => this.handlePlaceChanged(clickResult)} />);
            break;
          case 'customplace':
            customPlaceAddresses.push(<ListItem primaryText={"LOCATION: " + a.name} secondaryText={clickResult.address} key={a.id} leftIcon={<MapsLocalHospital />} onClick={(event) => this.handlePlaceChanged(clickResult)} />);
            break;
          case 'pcp':
            clickResult.name = a.address_type_name;
            pcpAddress = (<ListItem primaryText={"PCP: " + a.name} secondaryText={clickResult.address} key={a.id} leftIcon={<ActionHome />} onClick={(event) => this.handlePlaceChanged(clickResult)} />);
            break;
          default:
            customAddresses.push(<ListItem primaryText={"LOCATION: " + a.name} secondaryText={clickResult.address} key={a.id} leftIcon={<MapsLocalHospital />} onClick={(event) => this.handlePlaceChanged(clickResult)} />);
            break;
        }
      }, this);
    }

    let locationType = (
      <List style={customListStyle}>
        {homeAddress}
        {workAddress}
        {customPlaceAddresses}
        <ListItem primaryText="Add Custom Shortcut" rightIcon={<ArrowDropRight />} leftIcon={<MapsLocalHospital />} onClick={(e) => this.handleAddAddress(e, 'customplace')} />
      </List>);

    let autosuggest;
    let addAddress = (<TextField onChange={(e) => this.searchAddress(e)} fullWidth={true} floatingLabelText={this.state.addLocationText} value={this.state.addLocationTextValue} />)
    let customLabel;
    if (this.state.addLocation && (this.state.addLocationType === 'custom' || this.state.addLocationType === 'customplace')) {
      customLabel = (<TextField onChange={(e) => this.addCustomLabel(e)} fullWidth={true} floatingLabelText={"Choose a short name for this address"} value={this.state.addLocationCustomLabel} />);
    }

    if (this.state.locationType === 'provider') {
      locationType = (
        <List style={customListStyle}>
          {pcpAddress}
          {customAddresses}
          <ListItem primaryText="Add Custom Shortcut" rightIcon={<ArrowDropRight />} leftIcon={<MapsLocalHospital />} onClick={(e) => this.handleAddAddress(e, 'custom')} />
        </List>)
      autosuggest = (<AutoComplete dataSourceConfig={datasourceConfig} dataSource={this.state.providers} filter={this.filterResults} maxSearchResults={5} onUpdateInput={this.updateTextSearch} fullWidth={true} floatingLabelText="Enter the Provider's name or address" onNewRequest={this.handleAutocomplete} searchText={this.state.inputValue} />)
    } else {
      autosuggest = (<AutoComplete dataSourceConfig={datasourceConfig} dataSource={this.state.providers} filter={this.filterResults} maxSearchResults={5} onUpdateInput={this.updateTextSearch} fullWidth={true} floatingLabelText="Enter the Member's address or a nearby intersection or public place" onNewRequest={this.handleAutocomplete} searchText={this.state.inputValue} />)
    }

    let listItem = (
      <div className="" id="container">
        {autosuggest}
        <List>
          {this.state.currentLocation}

        </List>

        <Divider />

        {locationType}
        <Divider />
        <List style={customListStyle}>
          {this.state.nearbyPlaces}
        </List>
      </div >
    )
    if (this.state.addLocation) {
      listItem = (
        <div className="" id="container">
          {addAddress}
          {customLabel}
          <SelectableList defaultValue={this.state.addLocationID}>
            {this.state.searchAddresses}
          </SelectableList>
        </div >)

      actions = [
        <FlatButton
          label="Back"
          primary={true}
          onClick={this.handleBack}
        />,
        <FlatButton
          label="Save"
          primary={true}
          keyboardFocused={true}
          onClick={this.handleSave}
        />,
      ];
    }

    return (
      <div style={buttonStyleWhite} >
        {button}
        <Dialog
          contentStyle={customContentStyle}
          title={this.props.title}
          actions={actions}
          modal={true}
          open={this.state.open}
          onRequestClose={this.handleClose}
          autoScrollBodyContent={true}
        >
          {listItem}
        </Dialog>
      </div>
    );
  }
}