import React, { Component } from 'react';
import Images from '../assets/Images';
import { Checkbox, Button, InputAdornment, TextField, InputLabel, Typography, IconButton } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import api from '../api';
import Constant from '../library/Constant';
import { Link } from 'react-router-dom';

const CustomCheckbox = withStyles({
  root: {
    color: '#51c6ea',
    '&$checked': {
      color: '#51c6ea',
    },
  },
  checked: {},
})((props) => <Checkbox color="default" {...props} />);

class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      email: '',
      password: '',
      showPass: false,
      errorEmail: false,
      errorPassword: false,
      msgEmail: '',
      msgPassword: ''
    }
  }

  componentDidMount() {
    // this.coba()
  }

  handleChange(e) {
    let data = this.state
    this.setState({...data, [e.target.name] : e.target.value})
    if (e.target.name == "email") {
        this.setState({ errorEmail: false, msgEmail: '' })
    } else if (e.target.name) {
        this.setState({ errorPassword: false, msgPassword: '' })
    }
  }

  isEmail(email) {
    const 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(String(email).toLowerCase());
  }

  validateLogin() {
      var isEmail = this.isEmail(this.state.email)

      if (this.state.email.trim() == "") {
          this.setState({ errorEmail: true, msgEmail: 'Email harus diisi!' })
      } else if (!isEmail) {
        this.setState({ errorEmail: true, msgEmail: 'Format email tidak sesuai!' })
      } else if (this.state.password.trim() == "") {
          this.setState({ errorPassword: true, msgPassword: 'Password harus diisi!' })
      } else {
          this.login()
      }
  }

  login() {
    let payload = {
      "email": this.state.email,
      "password": this.state.password
  }
    api.create().login(payload).then((response) => {
      if (response.data.status === 'success') {
        localStorage.setItem(Constant.TOKEN, response.data.data.token)
        this.props.history.push('/home/beranda')
      } else {
        if (response.data.message == 'Password Salah!') {
            this.setState({ errorPassword: true, msgPassword: response.data.message })
        } else {
            this.setState({ errorEmail: true, msgEmail: response.data.message })
        }
      }
    })
  }

  render() {
    return (
      <div style={{ flex: 1, display: 'flex' }}>
        <div style={{ width: '50%', height: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }}>
          <img src={Images.tia} />
          <img src={Images.imageLogin} style={{ marginTop: 30 }} />
        </div>
        <div style={{ width: '50%', height: '100vh', backgroundColor: '#51c6ea', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }}>
          <div style={{ paddingTop: 56, paddingLeft: 54, paddingRight: 54, display: 'flex', flexDirection: 'column', width: 388, height: 441, borderRadius: 12, boxShadow: '0 2 4 0 rgba(0, 0, 0, 0.2)', backgroundColor: '#ffffff' }}>
            <img src={Images.tia} />

            <TextField
              label={<Typography style={{fontSize: 12, fontFamily: 'Nunito Sans, sans-serif'}}>Email *</Typography>}
              id="email"
              type={"text"}
              name={"email"}
              value={this.state.email}
              onChange={(email) => {
                  this.handleChange(email)
                }}
              variant="outlined"
              error={this.state.errorEmail}
              style={{ width: '100%', height: 51, marginTop: 32, fontSize: 14 }}
              helperText={this.state.msgEmail}
              InputProps={{
                endAdornment: <InputAdornment position="end"><img src={Images.email} /></InputAdornment>,
              }}
            />

            <TextField
              label={<Typography style={{fontSize: 12, fontFamily: 'Nunito Sans, sans-serif'}}>Kata Sandi *</Typography>}
              id="password"
              type={this.state.showPass ? 'text' : 'password'}
              name={"password"}
              value={this.state.password}
              onChange={(password) => {
                  this.handleChange(password)
                }}
              variant="outlined"
              error={this.state.errorPassword}
              style={{ width: '100%', height: 51, marginTop: this.state.errorEmail ? 35 : 20 }}
              helperText={this.state.msgPassword}
              InputProps={{
                endAdornment: <InputAdornment position="end">
                  <IconButton
                  aria-label="toggle password visibility"
                  style={{color: '#4b4b4b', opacity: 0.5}}
                  onClick={() => this.setState({showPass: !this.state.showPass})}
                  edge="end"
                >
                  {this.state.showPass ? <Visibility style={{fontSize: 18}} /> : <VisibilityOff style={{fontSize: 18}} />}
                </IconButton>
                </InputAdornment>,
              }}
            />

            <div style={{ flexDirection: 'row', width: '100%', marginTop: this.state.errorPassword ? 26 : 16 }}>
              <CustomCheckbox name="checked-remember" />
              <span style={{ color: 'rgba(0, 0, 0, 0.5)', fontSize: 12, fontFamily: 'Nunito Sans, sans-serif' }}>Remember Me</span>
              <Link to={{pathname: '/forgot-password'}} style={{textDecoration: 'none'}}><span style={{marginLeft: 30, color: '#51c6ea', cursor: 'pointer', fontSize: 12, fontFamily: 'Nunito Sans, sans-serif' }}>Lupa Kata Sandi?</span></Link>
            </div>
            <Button name="submit" variant="contained" disabled={this.state.email.trim() == '' && this.state.password.trim() == '' ? true : false} onClick={() => this.validateLogin()} style={{ marginTop: 23,  width: '100%', height: 35, borderRadius: 4, color: this.state.email.trim() == '' && this.state.password.trim() == '' ? '#4b4b4b' : '#fff', backgroundColor: this.state.email.trim() == '' && this.state.password.trim() == '' ? '#d8d8d8' : '#51c6ea' }}>
              <Typography style={{fontSize: 12, fontFamily: 'Nunito Sans, sans-serif'}}>Login</Typography>
            </Button>
          </div>
        </div>
      </div >
    );
  }
}

export default Login;