import React from 'react';
// import { withFormsy } from 'formsy-react';
import APPCONFIG from 'constants/Config';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import QueueAnim from 'rc-queue-anim';
import Dialog from 'material-ui/Dialog';

import Instance from '../../../components/Connection';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.setCookie('token', null, 0);
    this.state = {
      email: '',
      pass: '',
      message: '',
      open: false,
      errors: {
        email: "",
        pass: ""
      },
    }

    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }


  setCookie(cname, cvalue, date) {
    var d = new Date(date * 1000);
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  componentDidMount() {
    this.setState(Object.assign(this.state, { email: '', pass: '' }));
  }

  handleLogin(event, state) {
    event.preventDefault();
    var newErrors;
    var newErrors;
    var formIsValid;

    if (this.state.pass === "") {
      Object.assign(this.state, {
        newErrors: Object.assign(this.state.errors, { pass: "Password is required" })
      }
      );
      formIsValid = false;
    }
    else {
      newErrors: Object.assign(this.state.errors, { pass: "" })
    }

    if (this.state.email === "") {
      Object.assign(this.state, {
        newErrors: Object.assign(this.state.errors, { email: "Email is required" })
      }
      );
      formIsValid = false;
    }
    else {
      newErrors: Object.assign(this.state.errors, { email: "" })
    }

    if (formIsValid != false) {
      Instance.setToken(null).post('/v1/authenticate/portal', {
        email: state.state.email,
        pass: state.state.pass,
      }).then(function (res) {
        let auth = res.data;
        state.setCookie('token', auth.token, auth.valid_time);
        localStorage.setItem('loggedUser', JSON.stringify(auth.user));

        Instance.setToken(auth.token);

        location.href = '/#/';
      }).catch(function (err) {
        state.setState(Object.assign(state.state, {
          message: (err.response.data.message),
          open: true,
        }));
      });
    }
  }

  handleEmail(event, state) {
    event.preventDefault();
    state.setState(Object.assign(state.state, { email: event.currentTarget.value }));

    if (this.state.email === "") {
      // alert('yup')
      Object.assign(this.state, {
        newErrors: Object.assign(this.state.errors, { email: "Email is required" })
      }
      );
      // formIsValid = false;   
    }
    else {
      newErrors: Object.assign(this.state.errors, { email: "" })
    }
  }

  handlePass(event, state) {
    event.preventDefault();
    state.setState(Object.assign(state.state, { pass: btoa(event.currentTarget.value) }));

    var NewErrors;
    if (this.state.pass === "") {
      // alert('yup')
      Object.assign(this.state, {
        newErrors: Object.assign(this.state.errors, { pass: "Password is required" })
      }
      );
      // formIsValid = false;   
    }
    else {
      newErrors: Object.assign(this.state.errors, { pass: "" })
    }
  }

  handleOpen = () => {
    // this.setState({ open: true });

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

  handleClose = () => {
    this.setState(Object.assign(this.state, { open: false }));
    // this.setState({ open: false });
  };

  render() {
    const actions = [
      <FlatButton
        label="Dismiss"
        primary={true}
        onClick={this.handleClose}
      />,
    ];

    return (
      <div className="body-inner">
        <div className="card bg-white">
          <div className="card-content">

            <section className="logo text-center">
              <h1><a href="#/">CHM Hub<sup>®</sup></a></h1>
            </section>

            <form className="form-horizontal">
              <fieldset>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Email"
                    errorText={this.state.errors.email}
                    type="email"
                    fullWidth
                    ref="email"

                    onBlur={(event) => this.handleEmail(event, this)}
                  />
                </div>
                <div className="form-group">
                  <TextField
                    floatingLabelText="Password"

                    errorText={this.state.errors.pass}

                    // errorText="Use at least 8 characters, including both an uppercase letter and a special character"
                    type="password"
                    fullWidth
                    ref="pass"
                    onBlur={(event) => this.handlePass(event, this)}
                  />
                </div>
              </fieldset>
            </form>
          </div>
          <div className="card-action no-border text-right">
            <a href="#/" className="color-primary" onClick={(event) => this.handleLogin(event, this)}>Login</a>
          </div>
        </div>

        <div className="additional-info">
          {/* <a href="#/sign-up">Sign up</a>
          <span className="divider-h" /> */}
          <a href="#/forgot-password">Forgot your password?</a>
        </div>

        <Dialog
          title="Login Error"
          actions={actions}
          modal={false}
          open={this.state.open}
          onRequestClose={this.handleClose}
        >
          {this.state.message}
        </Dialog>
      </div>
    );
  }
}

const Page = () => (
  <div className="page-login">
    <div className="main-body">
      <QueueAnim type="bottom" className="ui-animate">
        <div key="1">

          <Login />
        </div>
      </QueueAnim>
    </div>
  </div>
);

module.exports = Page;
