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 = {
      "name": "",
      "first": "",
      "last": "",
      "gender": "",
      "member": "",
      "email": "",
      "phonenumber": "",
      "pass": "",
      "birthdate": new Date(),
      "validated": false,
      "passwordValidated": false,
      "passConfirmation": "",
      "organizationType": { name: "", key: "provider", desc: "" },
      "planName": {
        "id": "",
        "type": {
          "name": "",
          "key": "provider"
        },
        "name": ""
      },
      "role": { name: "", key: "SP", desc: "" },
      "profiles": [],
      "types": [],
      "organizations": [],
      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.clickEvent = this.clickEvent.bind(this);
    this.handleChangeProfile = this.handleChangeProfile.bind(this);
    this.handleChangeType = this.handleChangeType.bind(this);
    this.handleChangeOrganization = this.handleChangeOrganization.bind(this);
    this.getRoles = this.getRoles.bind(this);
    this.getOrganizations = this.getOrganizations.bind(this);
  }

  componentDidMount = () => {
    const self = this;
    Instance.getRawConn().get('/v1/nemt/organization/type').then(function (res) {
      const types = res.data.map(p => {
        if (p.key === "provider") {
          self.setState(Object.assign(self.state, { organizationType: p }));
        }
        return (<MenuItem value={p} primaryText={p.name} />);
      });
      self.setState(Object.assign(self.state, { types: types }));
      let organizations = self.getOrganizations(self.state.organizationType.key);
      let roles = self.getRoles(self.state.organizationType.key)

      Promise.all([organizations, roles]).then(console.log).catch(console.error);
    }).catch(function (err) {
      console.error('Error to get types: ', err);
    });
  }

  getRoles = (orgType) => {
    const self = this;
    return new Promise((resolve, reject) => {
      Instance.getRawConn().get(`/v1/nemt/profile/org/${orgType}`).then(function (res) {
        const profiles = res.data.map((p, i) => {
          if (i === 0) {
            self.setState(Object.assign(self.state, { role: p }));
          }
          return (<MenuItem value={p} primaryText={p.name} />);
        });

        self.setState(Object.assign(self.state, { profiles: profiles }));
        resolve(res.data);
      }).catch(function (err) {
        console.log('Error to get roles: ', err)
        reject(err);
      });
    });
  }

  getOrganizations = (orgType) => {
    const self = this;
    return new Promise((resolve, reject) => {
      Instance.getRawConn().get(`/v1/nemt/organization?type=${orgType}`).then(function (res) {
        const orgs = res.data.map((p, i) => {
          if (i === 0) {
            self.setState(Object.assign(self.state, { planName: p }));
          }
          return (<MenuItem value={p} primaryText={p.name} />);
        });

        if (orgs.length > 0) {
          self.setState(Object.assign(self.state, { organizations: orgs }));
        } else {
          self.setState(Object.assign(self.state, { organizations: null }));
        }
        resolve(res.data);
      }).catch(function (err) {
        console.log('Error to get organizations: ', err)
        reject(err);
      });
    });
  }

  buttonValidated = () => {
    let validated = true;
    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.email || this.state.email === null || this.state.email === "") validated = false;
    if (!this.state.phonenumber || this.state.phonenumber === null || this.state.phonenumber === "") validated = false;
    if (!this.state.passwordValidated || !this.state.pass || this.state.pass === null || this.state.pass === "") validated = false;
    if (!this.state.role || this.state.role === null || this.state.role.key === "") validated = false;
    if (!this.state.organizationType || this.state.organizationType === null || this.state.organizationType.key === "") validated = false;
    if (!this.state.planName || this.state.planName === null || this.state.planName.id === "") validated = false;

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

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

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

  // handleChange = (event, index, value) => {
  //   this.setState(Object.assign(this.state, { gender: value }));
  //   this.buttonValidated();
  // };

  // handleMember = (event) => {
  //   this.setState(Object.assign(this.state, { member: 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, { phonenumber: phone }));
  };

  handlePass = (event) => {
    this.setState(Object.assign(this.state, { pass: btoa(event.target.value) }));
    this.setState(Object.assign(this.state, { passwordValidated: 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, { passwordValidated: this.state.pass === this.state.passConfirmation }));
  };

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

  handleChangeType = (event, key, payload) => {
    const self = this;
    this.setState(Object.assign(this.state, { organizationType: payload }));
    let organizations = this.getOrganizations(payload.key);
    let roles = this.getRoles(payload.key);

    Promise.all([organizations, roles]).then(console.log).catch(console.error);
  }

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


  // handleDate = (event, date) => {
  //   this.setState(Object.assign(this.state, { birthdate: date }));
  //   this.buttonValidated();
  // };

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

    let user = {
      "name": this.state.first + ' ' + this.state.last,
      "first": this.state.first,
      "last": this.state.last,
      "email": this.state.email,
      "phonenumber": this.state.phonenumber,
      "pass": this.state.pass,
      "profiles": [this.state.role],
      "organizations": [this.state.planName],
      "types": [this.state.organizationType],
    }

    Instance.getRawConn().post('/v1/nemt/users/portal', 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">
                  <SelectField
                    floatingLabelText="Organization Type"
                    value={this.state.organizationType}
                    onChange={this.handleChangeType}
                    fullWidth={true}
                  >
                    {this.state.types}
                  </SelectField>
                </div>


                <div className="form-group">
                  <SelectField
                    floatingLabelText="Organization Name"
                    value={this.state.planName}
                    onChange={this.handleChangeOrganization}
                    fullWidth={true}
                  >
                    {this.state.organizations}
                  </SelectField>
                </div>


                <div className="form-group">
                  <SelectField
                    floatingLabelText="Role"
                    onChange={this.handleChangeProfile}
                    value={this.state.role}
                    fullWidth={true}
                  >
                    {this.state.profiles}
                  </SelectField>
                </div>


                <div className="form-group">
                  <TextField
                    floatingLabelText="Email"
                    type="email"
                    fullWidth
                    onChange={this.handleEmail}
                    onBlur={this.buttonValidated}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Mobile Phone"
                    type="telephone"
                    fullWidth
                    onChange={this.handlePhone}
                    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="Choose Password"
                    type="password"
                    fullWidth
                    onChange={this.handlePass}
                    onBlur={this.buttonValidated}
                  />
                  <TextField
                    floatingLabelText="Verify Password"
                    type="password"
                    fullWidth
                    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;
