import React, { Component } from 'react';
import { Media, Button, Card, CardBody,CardTitle, 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 Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email:"",
      password:"",
      errorEmail:"",
      errorPass:"",
      user:null,
      toke:""
    }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.logChange = this.logChange.bind(this);
    this.validate = this.validate.bind(this);
  }
  logChange(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: '/admin',
        state:{
        }
      });
    }
  }
  render() {
    return (
      <MuiThemeProvider muiTheme={muiTheme}>
        <div className="app flex-row align-items-center login-page">
          <Container className="login-container">
            <Row className="justify-content-center">
              <Media className="logo">
                <Media object src="./public/resources/images/DonecLogo.svg" alt="Generic placeholder image" />
              </Media>
            </Row>
            <Row className="justify-content-center">
              <Col md="4" sx="2">
                <CardGroup>
                  <Card className="p-4">
                    <CardBody>
                      <CardTitle>Iniciar sesión con su cuenta</CardTitle>
                      <InputGroup className="mb-3">
                       <TextField
                             hintText="Correo electronico"
                             floatingLabelFixed
                             name="email"
                             errorText={this.state.errorEmail}
                             onChange={this.logChange} 
                             value={this.state.email}/>
                      </InputGroup>
                      <InputGroup className="mb-4">
                        <TextField
                              hintText="Contraseña"
                              floatingLabelFixed
                              errorText={this.state.errorPass}
                              type="password"
                              name="password"
                              onChange={this.logChange}
                              value={this.state.password}/>
                      </InputGroup>
                      <div className="footer-form">
                        <Button color="warning" size="lg" block onClick={this.handleSubmit}>Acceder</Button>
                        <Button color="link" className="center">¿Olvidó su contraseña?</Button>
                      </div>
                    </CardBody>
                  </Card>
                </CardGroup>
              </Col>
            </Row>
          </Container>
        </div>
      </MuiThemeProvider>
    );
  }
}

export default withRouter(Login);
