import React from 'react';
import Dialog from 'material-ui/Dialog';
import { List, ListItem } from 'material-ui/List';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const placeService = new google.maps.places.PlacesService(document.createElement('div'));

export default class GoogleAddressComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      buttonValue: '',
      openDialog: false,
      title: '',
      modalStyle: {
        width: '100%',
        maxWidth: '600px',
      },
      divStyle: {
        textAlign: 'left',
        textTransform: 'none !important',
        padding: '0px 5px 0px 0px',
        marginTop: -5,
        boxShadow: 'none',
        color: 'rgba(0, 0, 0, 0.3)',
      },
      location: {
        lat: 41.819078,
        long: -87.623129,
      },
      searchAddresses: [],
      selectedAddress: {
        id: '',
        address: '',
        lat: 0,
        lng: 0,
        name: '',
        text: '',
      },
      showType: false,
      addressType: '',
    };

    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.setProps = this.setProps.bind(this);
    this.handleSave = this.handleSave.bind(this);
    this.handleSearch = this.handleSearch.bind(this);
    this.handleName = this.handleName.bind(this);
    this.handleAddress = this.handleAddress.bind(this);
    this.handleChangeType = this.handleChangeType.bind(this);
  }

  componentDidMount() {
    this.setProps(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.setProps(nextProps);
  }

  setProps(propsParam) {
    this.setState(Object.assign(this.state, { buttonValue: propsParam.buttonValue, title: propsParam.title, showType: propsParam.showType }));
  }

  handleChangeType = (event, key, payload) => {
    this.setState(Object.assign(this.state, { addressType: payload }));
  }

  handleOpen() {
    this.setState(Object.assign(this.state, { openDialog: true }));
  }

  handleClose() {
    this.setState(Object.assign(this.state, { openDialog: false }));
  }

  handleSave() {
    this.setState(Object.assign(this.state, { openDialog: false }));
    let selectedAddress = this.state.selectedAddress;
    if (this.state.showType) {
      selectedAddress.address_type = this.state.addressType;
    }

    if (this.props.onSelectAddress) {
      this.props.onSelectAddress(selectedAddress);
    }
  }

  handleAddress(e, a) {
    this.setState(Object.assign(this.state, { selectedAddress: a }));
  }

  handleName(e) {
    let selectedAddress = this.state.selectedAddress;
    selectedAddress.name = e.target.value;
    this.setState(Object.assign(this.state, { selectedAddress: selectedAddress }));
  }

  handleSearch(e) {
    var location = new google.maps.LatLng(this.state.lat, this.state.long);
    var request = {
      location: location,
      radius: '500',
      query: e.target.value,
    };

    let selectedAddress = this.state.selectedAddress;
    selectedAddress.text = e.target.value;
    this.setState(Object.assign(this.state, { selectedAddress: selectedAddress }));

    const callback = (results, status) => {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        const googlePlaces = results.map(place => {
          const address = (place.formatted_address ? place.formatted_address : place.vicinity);
          place = Object.assign(place, { text: `${address}` });
          const clickResult = {
            id: place.id,
            address: place.formatted_address ? place.formatted_address : place.vicinity,
            lat: place.geometry.location.lat(),
            lng: place.geometry.location.lng(),
            name: place.name,
            text: place.text,
            type: 'google',
          };

          return (<ListItem value={place.id} primaryText={place.name} secondaryText={clickResult.address} key={place.id} onClick={(e) => this.handleAddress(e, clickResult)} />);
        });
        this.setState(Object.assign(this.state, { searchAddresses: googlePlaces }));
      }
    }

    placeService.textSearch(request, callback);
  }

  render() {

    let actions = [
      <FlatButton
        label="Cancel"
        primary={false}
        onClick={this.handleClose}
      />,
      <FlatButton
        label="Add Address"
        primary={true}
        fullWidth={false}
        keyboardFocused={true}
        onClick={this.handleSave}
      />,
    ];

    let addressType = (
      <SelectField
        floatingLabelText="Address Type"
        value={this.state.addressType}
        onChange={this.handleChangeType}
        fullWidth={false}
      >
        <MenuItem value={"home"} primaryText={"Home"} />
        <MenuItem value={"work"} primaryText={"Work"} />
        <MenuItem value={"customplace"} primaryText={"Custom Address"} />
      </SelectField>
    )

    return (
      <div style={this.state.divStyle} >
        <RaisedButton
          label={this.state.buttonValue}
          onClick={this.handleOpen}
          secondary
          fullWidth={false}
        />
        <Dialog
          contentStyle={this.state.modalStyle}
          fullWidth={false}
          title={this.state.title}
          actions={actions}
          modal={true}
          open={this.state.openDialog}
          onRequestClose={this.handleClose}
          autoScrollBodyContent={true}
        >
          <div className="" id="container">
            {addressType}
            <TextField fullWidth={false} onChange={this.handleSearch} floatingLabelText={"Address, Intersection or Place"} value={this.state.selectedAddress.text} />
            <TextField fullWidth={false} onChange={this.handleName} floatingLabelText={"Short Label"} value={this.state.selectedAddress.name} />
            <List>
              {this.state.searchAddresses}
            </List>
          </div>
        </Dialog>
      </div>);
  }
}