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 IconButton from 'material-ui/IconButton';
import Popover from 'material-ui/Popover';
import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble';
import { indigo500 } from 'material-ui/styles/colors';
import CommunicationEmail from 'material-ui/svg-icons/communication/email';
import CommunicationTextsms from 'material-ui/svg-icons/communication/textsms';
import CommunicationCall from 'material-ui/svg-icons/communication/call';
import Close from 'material-ui/svg-icons/navigation/close';
import $ from 'jquery';
import Instance from '../../../components/Connection';

export default class ContactList extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      open: false,
      data: {
        driverMobile: "",
        memberMobile: "",
        memberEmail: "",
        schedulerEmail: "",
        schedulerMobile: "",
        rideID: "",
      },
      anchorEl: null,
      formMode: 'hide',
      formDisplay: 'none',
      message: '',
    };
    this.handleMobileCall = this.handleMobileCall.bind(this);
    this.handleMailTo = this.handleMailTo.bind(this);
    this.handleSMS = this.handleSMS.bind(this);
    this.handleCancelMessage = this.handleCancelMessage.bind(this);

    this.handleClick = this.handleClick.bind(this);
    this.handleRequestClose = this.handleRequestClose.bind(this);
    this.handleMessage = this.handleMessage.bind(this);
    this.handleMessageField = this.handleMessageField.bind(this);
    this.handleSend = this.handleSend.bind(this);
  }


  componentDidMount = () => {
    const self = this;
    if (this.props.data && this.props.data !== null) {
      this.setState(Object.assign(this.state, { data: this.props.data }));
    }
  }

  componentWillReceiveProps = (nextProps) => {
    const self = this;
    if (nextProps.data && nextProps.data !== null) {
      this.setState(Object.assign(this.state, { data: nextProps.data }));
    }
  }

  handleDriverMessage = (message) => {
    const rideID = this.state.data.rideID;
    let url = '/v1/nemt/rides/' + rideID + '/message/driver';
    url = encodeURI(url);
    Instance.getRawConn().post(url, { message: message }).then(function (res) {
      alert('Message Send');
    }).catch(function (err) {
      console.error(err);
    });
  }

  handleMessage = (message) => {
    const rideID = this.state.data.rideID;
    let url = '/v1/nemt/rides/' + rideID + '/message';
    url = encodeURI(url);
    return Instance.getRawConn().post(url, { message: message });
  }

  handleCancelMessage = () => {
    event.preventDefault();
    this.setState(Object.assign(this.state, { formDisplay: 'none', open: false }));
    console.log("handleCancelMessage")
  };

  handleMailTo = (event, to, from, subject) => {
    event.preventDefault();
    this.setState(Object.assign(this.state, { formMode: subject, formDisplay: 'block' }));
    console.log("handleMailTo" + to + from + subject)
  };

  handleMobileCall = (event, to, from, subject) => {
    event.preventDefault();
    this.setState(Object.assign(this.state, { formMode: subject, formDisplay: 'none' }));
    // window.open("tel:" + this.state.memberMobile );
    window.open("tel:" + to);

    console.log("handleMobileCall" + "to " + to + "from " + from)
  };

  handleSMS = (event, toMobilePhone, fromMobilePhone, subject) => {
    event.preventDefault();
    this.setState(Object.assign(this.state, { formMode: subject, formDisplay: 'block', message: '' }));
  }

  handleSend = (event, toMobilePhone, fromMobilePhone, subject) => {
    event.preventDefault();
    const self = this;
    self.handleMessage(self.state.message).then(res => {
      alert('Message Sent');
      self.setState(Object.assign(self.state, { formMode: '', formDisplay: 'none', message: '' }));
    }).catch(console.error);
  };

  handleClick = (event) => {
    event.preventDefault();
    this.setState(Object.assign(this.state, { open: true, anchorEl: event.currentTarget }));
  };

  handleRequestClose = () => {
    this.setState(Object.assign(this.state, { formDisplay: 'none' }));
    this.setState(Object.assign(this.state, { open: false }));
  };

  handleMessageField = (e) => {
    this.setState(Object.assign(this.state, { message: e.target.value }));
  }

  render() {
    return (
      <div style={{ "padding": '0px', 'margin': '0px', 'align': 'top', 'display': 'inline' }} >

        <a href="#" onClick={this.handleClick} > Contact </a>

        <Popover
          open={this.state.open}
          anchorEl={this.state.anchorEl}
          anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
          targetOrigin={{ horizontal: 'left', vertical: 'top' }}
          onRequestClose={this.handleRequestClose}
        >

          <div id="popoverContentWrapper" >

            <div id="smsFormWrapper" style={{ display: this.state.formDisplay }}>

              <form className="form-vertical" style={{ paddingLeft: '20px', paddingRight: '20px' }} >
                <fieldset>
                  <div className="form-group">
                    <TextField
                      floatingLabelText="Subject"
                      hintText="Subject"
                      value={this.state.formMode}
                    // errorText="This field is required.
                    // onChange={this.handleFirst}
                    // onBlur={this.buttonValidated}
                    />
                  </div>

                  <div className="form-group">
                    <TextField
                      floatingLabelText="Message"
                      hintText="Message Field"
                      errorText="This field is required."
                      multiLine={true}
                      rows={3}
                      onChange={this.handleMessageField}
                      value={this.state.message}
                    // onBlur={this.buttonValidated}
                    />
                  </div>

                  <div className="form-group">
                    <RaisedButton
                      label="Send"
                      primary={true}
                      onClick={this.handleSend}
                    // disabled={!this.state.validated}
                    />
                    <RaisedButton
                      label="Cancel"
                      onClick={this.handleCancelMessage}
                    // disabled={!this.state.validated}
                    />
                  </div>

                  <div className="divider" />
                  <div className="form-group">
                    <p className="text-small">By clicking Send, you agree to <a href="javascript:;"><i>terms</i></a> and <a href="javascript:;"><i>privacy policy</i></a></p>
                  </div>
                </fieldset>
              </form>
            </div>

            <div id="contactListWrapper" >
              <List>
                <ListItem
                  leftIcon={<CommunicationCall color={indigo500} onTouchTap={(e) => this.handleMobileCall(e, this.state.data.driverMobile, this.state.data.schedulerMobile, "Call to Driver from Scheduler")} />}
                  insetChildren={true}
                  rightIcon={<CommunicationChatBubble color={indigo500} onTouchTap={(e) => this.handleSMS(e, this.state.data.driverMobile, this.state.data.schedulerMobile, "SMS to Driver from Scheduler")} />}
                  primaryText={this.state.data.driverMobile}
                  secondaryText="Driver"
                />
                <ListItem
                  leftIcon={<CommunicationCall color={indigo500} onTouchTap={(e) => this.handleMobileCall(e, this.state.data.memberMobile, this.state.data.schedulerMobile, "Call to Member from Scheduler")} />}
                  insetChildren={true}
                  rightIcon={<CommunicationChatBubble color={indigo500} onTouchTap={(e) => this.handleSMS(e, this.state.data.memberMobile, this.state.data.schedulerMobile, "SMS to Member from Scheduler")} />}
                  primaryText={this.state.data.memberMobile}
                  secondaryText="Member"
                />
                <ListItem color={indigo500}
                  leftIcon={<CommunicationEmail onTouchTap={(e) => this.handleMailTo(e, this.state.data.memberEmail, 'no-reply@hcmhub.com', 'Email to Member from Scheduler')} />}
                  primaryText={this.state.data.memberEmail}
                  secondaryText="Member"
                />
              </List>
            </div>

          </div>
        </Popover>

      </div>
    );
  }
}

ContactList.PropTypes = {
  data: PropTypes.object.isRequired,
}