import React from 'react';
import { browserHistory, Redirect } from 'react-router';
import APPCONFIG from 'constants/Config';
import TextField from 'material-ui/TextField';
import QueueAnim from 'rc-queue-anim';

import AutoComplete from 'material-ui/AutoComplete';
import MenuItem from 'material-ui/MenuItem';
import SelectField from 'material-ui/SelectField';
import { Tabs, Tab } from 'material-ui/Tabs';
import Slider from 'material-ui/Slider';
import TimePicker from 'material-ui/TimePicker';
import DatePicker from 'material-ui/DatePicker';
import RaisedButton from 'material-ui/RaisedButton';

import Toggle from 'material-ui/Toggle';
import Snackbar from 'material-ui/Snackbar';
import Instance from '../../../components/Connection';

class SignUp extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;

    this.state = {
      "provider_name": "",
      "provider_npi": "",
      "name": "",
      "first": "",
      "last": "",
      "gender": "",
      "member": "",
      "email": "",
      "phone_number": "",
      "pass": "",
      "birthdate": new Date(),
      "validated": false,
      "password_validated": false,
      "passConfirmation": "",
      "organizationType": { name: "", key: "provider", desc: "" },
      showValidationErrors: false,
      validationErrors: []
    }

    this.buttonValidated = this.buttonValidated.bind(this);
    this.handleFirst = this.handleFirst.bind(this);
    this.handleLast = this.handleLast.bind(this);
    this.handleEmail = this.handleEmail.bind(this);
    this.handlePhone = this.handlePhone.bind(this);
    this.handlePass = this.handlePass.bind(this);
    this.handleConfirmationPass = this.handleConfirmationPass.bind(this);
    this.handleProviderName = this.handleProviderName.bind(this);
    this.handleProviderNPI = this.handleProviderNPI.bind(this);
    this.clickEvent = this.clickEvent.bind(this);
  }

  componentDidMount = () => {
  }

  buttonValidated = () => {
    let validated = true;
    if (!this.state.provider_name || this.state.provider_name === null || this.state.provider_name === "") validated = false;
    if (!this.state.provider_npi || this.state.provider_npi === null || this.state.provider_npi === "") validated = false;
    if (!this.state.email || this.state.email === null || this.state.email === "") validated = false;
    if (!this.state.phone_number || this.state.phone_number === null || this.state.phone_number === "") validated = false;
    if (!this.state.first || this.state.first === null || this.state.first === "") validated = false;
    if (!this.state.last || this.state.last === null || this.state.last === "") validated = false;
    if (!this.state.password_validated || !this.state.pass || this.state.pass === null || this.state.pass === "") validated = false;

    this.setState(Object.assign(this.state, { validated: validated }));
  }

  handleProviderName = (event) => {
    this.setState(Object.assign(this.state, { provider_name: event.target.value }));
  };

  handleProviderNPI = (event) => {
    this.setState(Object.assign(this.state, { provider_npi: event.target.value }));
  };

  handleFirst = (event) => {
    this.setState(Object.assign(this.state, { first: event.target.value }));
  };

  handleLast = (event) => {
    this.setState(Object.assign(this.state, { last: event.target.value }));
  };

  handleEmail = (event) => {
    this.setState(Object.assign(this.state, { email: event.target.value }));
  };

  handlePhone = (event) => {
    let phone = event.target.value;
    if (phone.indexOf("+1") < 0 && phone.length == 10) {
      phone = "+1" + phone;
      phone = phone.substring(0, 12);
    }

    this.setState(Object.assign(this.state, { phone_number: phone }));
  };

  handlePass = (event) => {
    this.setState(Object.assign(this.state, { pass: btoa(event.target.value) }));
    this.setState(Object.assign(this.state, { password_validated: this.state.pass === this.state.passConfirmation }));
  };

  handleConfirmationPass = (event) => {
    this.setState(Object.assign(this.state, { passConfirmation: btoa(event.target.value) }));
    this.setState(Object.assign(this.state, { password_validated: this.state.pass === this.state.passConfirmation }));
  };

  clickEvent = (event) => {
    event.preventDefault();
    const state = this;

    let user = {
      "provider":
        {
          "org_name": this.state.provider_name,
          "internal_id": this.state.provider_npi
        },
      "name": this.state.first + ' ' + this.state.last,
      "first": this.state.first,
      "last": this.state.last,
      "email": this.state.email,
      "phonenumber": this.state.phone_number,
      "pass": this.state.pass,
    };

    Instance.getRawConn().post('/v1/selfregister/', user).then(function (res) {
      localStorage.removeItem('loggedUser');
      location.href = '/#/login';
    }).catch(function (err) {
      if (err.response.status === 422) {
        //Unprocessable Entity (validation failed)
        state.setState(Object.assign(state.state, {
          showValidationErrors: true,
          validationErrors: err.response.data.data
        }));
      } else {
        alert('Error to log in: ' + err.message);
      }
      console.error(err);
    });
  }

  handleDismiss() {
    this.setState(Object.assign(this.state, { showErrorMessage: false }));
  }

  render() {
    let validationErrors = null;
    if (this.state.showValidationErrors) {
      validationErrors = (
        <ul>
          {this.state.validationErrors.map(errorMessage => {
            const oneValidationMessage = (<li>{errorMessage.message}</li>);
            const oneValidationMessageWithTab = (<span><li style={{ marginLeft: 2 + "em" }}>{errorMessage.message}</li></span>);

            if (errorMessage.field_name === "password-tab") {
              return oneValidationMessageWithTab;
            } else {
              return oneValidationMessage;
            }
          })}
        </ul>
      );
    }

    return (
      <div className="body-inner">

        <div className="card bg-white">
          <div className="card-content">
            <section className="logo text-center">
              <h1><a href="#/">CHMHub®</a></h1>
            </section>

            <form className="form-horizontal">
              <fieldset>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Provider Organization Name"
                    fullWidth
                    onChange={this.handleProviderName}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Provider NPI"
                    type="number"
                    onChange={this.handleProviderNPI}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="First Name"
                    fullWidth
                    onChange={this.handleFirst}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Last Name"
                    fullWidth
                    onChange={this.handleLast}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Your Work Email"
                    type="email"
                    fullWidth
                    onChange={this.handleEmail}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Your Mobile Phone"
                    type="telephone"
                    onChange={this.handlePhone}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Choose Password"
                    type="password"
                    onChange={this.handlePass}
                    onBlur={this.buttonValidated}
                  />
                  <TextField
                    floatingLabelText="Verify Password"
                    type="password"
                    onChange={this.handleConfirmationPass}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="divider" />
                <div className="form-group">
                  <p className="text-small">By clicking on sign up, you agree to <a href="javascript:;"><i>terms</i></a> and <a href="javascript:;"><i>privacy policy</i></a></p>
                </div>
                <div className="divider" />
                <div className="form-group">
                  {validationErrors}
                </div>
              </fieldset>
            </form>
          </div>
          <div className="card-action no-border text-right">
            <a href="#/login" className="color-gray-light">Login</a>
            <RaisedButton
              label="Sign up"
              primary={true}
              onClick={this.clickEvent}
              disabled={!this.state.validated}
            />
          </div>
        </div>

      </div>
    );
  }
}

const Page = () => (
  <div className="page-login">
    <div className="main-body">
      <QueueAnim type="bottom" className="ui-animate">
        <div key="1">
          <SignUp />
        </div>
      </QueueAnim>
    </div>
  </div>
);

module.exports = Page;
