import React, { Component } from 'react';
import { Link } from 'react-router';
import { loginWithAzureAD } from '../actions/loginActions';
import { organisationList } from '../actions/userActions';
import { updateFormField } from '../actions/formActions';
import { connect } from 'react-redux';
import { reduxForm, reset } from 'redux-form';
import { setCookie } from '../utils/helpers.jsx';

class LoginSter extends Component {
  /** */
  componentWillMount() {
    let { dispatch } = this.props;
    let { query } = this.props.location;

    if(query && query.code) {
      dispatch(loginWithAzureAD(query.code))
        .then(dispatch(organisationList()));
    }
  }

  /** */
  handleSubmit(data) {
    setCookie('ster_orgcode', data.orgcode, 1);
    this.context.router.push('/dashboard');
  }

  /**
  * Login link
  */
  render() {
    const {
      fields: {
        orgcode,
      },
      handleSubmit,
      organisationList
    } = this.props;
    const { query } = this.props.location;

    let component = null;
    if(query && query.code && organisationList !== null) {
      component = (<div>
          <form className="loginForm" onSubmit={handleSubmit(this.handleSubmit.bind(this))}>
            <div className="innerForm">
              <div className="form-group">
                <label>Organisatie code</label>
                <select className="form-control" {...orgcode}>
                  <option value="">Kies een organisatie</option>
                  <option value="">---</option>
                  {organisationList.map(o => <option key={o.orgCode} value={o.orgCode}>{o.orgName}</option>)}
                </select>
              </div>
              <div className="form-group">
                <button type="submit" className="btn btn-default">Kies organisatie</button>
              </div>
            </div>
          </form>
        </div>);
    }
    else {
      component = (<div>
        <p>Je bent niet correct ingelogd.</p>
      </div>);
    }

    return component;
  }
}

LoginSter.contextTypes = {
  router: React.PropTypes.object.isRequired
};

LoginSter = reduxForm({
  form: 'loginSter',
  fields: [
    'orgcode',
  ]
}, (state) => {
  return {
    auth: state.auth,
    organisationList: state.organisationList
  };
})(LoginSter);

export default LoginSter;
