import Api from './api.js';
import App from './app.js';
import classNames from 'classnames';
import React from 'react';

class PasswordResetForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {'hideMsg': true, 'msg': '', 'msgOk': false, 'email': ''};
  }

  handleSubmit = (e) => {
    Api.Call('RESET_PASSWORD', {'email': this.state.email}, function(err, status, data) {
      if (err) {
        console.error(err, data);
        this.displayMessage(App.errorCodeToMessage(err.code), false);
        return;
      }

      this.displayMessage('You will receive a reset link to reset your password.', true);
      if (this.props.onSuccess) {
        this.props.onSuccess();
      }

    }.bind(this));
    e.preventDefault();
  }

  handleEmailChange = (event) => {
    this.setState({'email': event.target.value});
  }

  hideMessage = () => {
    this.setState({'hideMsg': true});
  }

  displayMessage = (msg, ok) => {
    this.setState({'msg': msg, 'msgOk': ok, 'hideMsg': false});
  }

  render = () => {
    var cName = classNames('form-message', {'hidden': this.state.hideMsg, 'message-ok': this.state.msgOk});
    return (
        <div className="row sign-in">
          <div className="offset-1 col-10 box offset-md-4 col-md-4 text-center">
            <form role="form" onSubmit={this.handleSubmit}>
              <label className="w-100 text-left"><strong>Email address</strong></label>
              <input className="form-control" type="email" onChange={this.handleEmailChange} />
              <input className="form-control submit" type="submit" value="Reset" />
              <div className={cName}>{this.state.msg}</div>
            </form>
          </div>
        </div>
       );
  }
}

export default PasswordResetForm;
