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

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

  handleSubmit = (e) => {
    Api.Call('SIGNIN', {'password': this.state.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('OK', true);
      this.props.onSuccess(data.token, data.isAdmin);

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

  handlePasswordChange = (event) => {
    this.setState({'password': event.target.value});
  }

  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 (
        <React.Fragment>
        <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} />
              <span className="w-100 d-inline-block text-left">
                <label><strong>Password</strong></label>
                <a className="blue-link hint-text float-right" href="/reset-password">Forgot password?</a>
              </span>
              <input className="form-control" type="password" onChange={this.handlePasswordChange} />
              <input className="form-control submit" type="submit" value="Sign In" />
              <div className={cName}>{this.state.msg}</div>
            </form>
          </div>
        </div>
        <div className="row">
          <div className="offset-1 col-10 box offset-md-4 col-md-4 text-center">
            <span>New to CryptoPF? <a href="#" className="blue-link" onClick={App.onInternNavigation.bind(this, '/signup')}>Create an account.</a></span>
          </div>
        </div>
        </React.Fragment>
       );
  }
}

export default SigninForm;

