import React, { Component } from 'react';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import Constants from '../../../helper/Constants.jsx';
import { browserHistory } from 'react-router';
import { withRouter } from 'react-router';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {cyan500,blue500,lightBlue500,grey50} from 'material-ui/styles/colors';
import TextField from 'material-ui/TextField';
import { onLogin } from '../../../actions/Login.jsx'
import store from '../../../store.jsx'
import Validation from 'react-validation';

const muiTheme = getMuiTheme({
  palette: {
    textColor: grey50,
    primaryText:grey50,
    primary1Color:blue500
  },
  appBar: {
    height: 50,
  },
});


class Install extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email:"",
      password:"",
      errorEmail:"",
      errorPass:"",
      user:null,
      toke:""
    }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.validate = this.validate.bind(this);
  }
  handleChange(e) {
     this.setState({[e.target.name]: e.target.value});  
  }
  validateEmail(value){
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(value);
  }
  isRequired(e){
    const name = e.target.name;
    const value = e.target.value;
    console.log(name);
  }
  validate(){
    let isValid = true;
    const errors = {};
    const state = this.state;
    if(!this.validateEmail(this.state.email)){
      isValid = false;
      errors.errorEmail = "No es un correo valido";
    }
    if(!isValid){
      this.setState(
        errors
     );
    }
    console.log(isValid,state);
    return isValid;
  }
  handleSubmit(e){
    e.preventDefault();
    const { history } = this.props || [];
    const { email, password } = this.state;
    const me = this;

    this.setState({
      errorEmail:"",
      errorPass:""
    });

    if(this.validate()){
      var data = {
        email,
        password
      }
      fetch(Constants.URL_LOGIN, {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(data)
      }).then(function(response) {
          if (response.status >= 400) {
            throw new Error("Bad response from server");
          }
          return response.json();
      }).then(function(response) {
          if(response.success){

             console.log(response);

             store.dispatch(onLogin({"user":response.user,"token":response.token}));

             
             localStorage.setItem("user",JSON.stringify(response.user));
             localStorage.setItem("token",response.token);
             localStorage.setItem("modules",JSON.stringify(response.user.usergroup.modules));
             
             /*history.push({
               pathname: '/projects',
               state:{
                user:response.user,
                token:response.token,
                modules:response.user.usergroup.modules
               }
             });*/
             // history.push("/");
             window.location.reload();
          }else{
            me.setState({
              errorEmail:response.msg,
              password:""
            });
          }
      }).catch(function(err) {
          console.log(err)
      });
    }
  }
  componentWillMount(){
    let {user} = localStorage;
    const { history } = this.props || [];
    if(user){
      history.push({
        pathname: '/',
        state:{
        }
      });
    }
  }
  render() {
    return (
      <MuiThemeProvider muiTheme={muiTheme}>
        <div className="app flex-row align-items-center">
          <Container>
            <Row className="justify-content-center">
              <Col md="8" sx="2">
                <CardGroup>
                  <Card className="p-4">
                    <CardBody>
                      <h1>Iniciar sesión</h1>
                      <p className="text-muted">Iniciar sesión en su cuenta</p>
                      <InputGroup className="mb-3">
                       <TextField
                             hintText="Correo electronico"
                             // floatingLabelText="Correo electronico o nombre de usuario"
                             floatingLabelFixed
                             name="email"
                             errorText={this.state.errorEmail}
                             onChange={this.handleChange} 
                             value={this.state.email}/>
                      </InputGroup>
                      <InputGroup className="mb-4">
                        <TextField
                              hintText="Contraseña"
                              // floatingLabelText="Contraseña"
                              floatingLabelFixed
                              errorText={this.state.errorPass}
                              type="password"
                              name="password"
                              onChange={this.handleChange}
                              value={this.state.password}/>
                      </InputGroup>
                      <Row>
                        <Col xs="6">
                          <Button color="primary" className="px-4" onClick={this.handleSubmit}>Acceder</Button>
                        </Col>
                        <Col xs="6" className="text-right">
                          <Button color="link" className="px-0">¿Olvidó su contraseña?</Button>
                        </Col>
                      </Row>

                    </CardBody>
                  </Card>
                  <Card className="text-white bg-primary py-5 d-md-down-none" style={{ width: 44 + '%' }}>
                    <CardBody className="text-center">
                      <div>
                        <h2>Regístrate</h2>
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                          labore et dolore magna aliqua.</p>
                        <Button color="primary" className="mt-3" active>¡Regístrate ahora!</Button>
                      </div>
                    </CardBody>
                  </Card>
                </CardGroup>
              </Col>
            </Row>
          </Container>
        </div>
      </MuiThemeProvider>
    );
  }
}

export default withRouter(Install);
