import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import { login } from '../../actions/auth';

import InstallWizard from './install/Wizard';

class Login extends React.Component {
  state = {
    loaded: false,
    installed: false,

    error: '',

    email: '',
    password: ''
  };

  constructor(props) {
    super(props);

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange({ target }) {
    const value = target.type === 'checkbox' ? target.checked : target.value;

    this.setState({
      [target.name]: value
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({ error: '' });

    this.props.login(this.state.email, this.state.password)
      .catch(err => {
        const error = err.response ? err.response.data.error : 'Unable to login';
        this.setState({ error: error });
      });
  }

  renderError() {
    if (!this.state.error) {
      return null;
    }

    return (
      <div className="login-error">{this.state.error}</div>
    );
  }

  render() {
    if (!this.props.site.installed) {
      return <InstallWizard/>;
    }

    return (
      <form onSubmit={this.handleSubmit}>
        <div className="box box-card box-center">
          <div className="columns no-gutters">
            <div className="column-6"><div className="login-image"/></div>
            <div className="column-6">
              <div className="box-header">
                <h1 className="box-title">DevCMS</h1>
                <p className="box-subtitle">Login to dashboard to start the adventure!</p>
              </div>

              <div className="box-content">
                <div className="field">
                  <label htmlFor="email">Email</label>
                  <input type="email" name="email" value={this.state.email} id="email" className="input-text" placeholder="john@doe.com" onChange={this.handleInputChange} required />
                </div>
                <div className="field">
                  <label htmlFor="password">Password</label>
                  <input type="password" name="password" value={this.state.password} id="password" className="input-text" placeholder="Minimum 8 characters" onChange={this.handleInputChange} required />
                  <Link to="#" className="btn btn-small btn-blue btn-link">Can't remember your password?</Link>
                </div>
                {this.renderError()}
              </div>

              <div className="box-footer">
                <button type="submit" className="btn btn-blue">Log In</button>
              </div>
            </div>
          </div>
        </div>
      </form>
    );
  }
}

export default connect(
  (state) => ({ site: state.site }),
  { login },
)(Login)
