import React, { Component } from 'react';
import Images from '../../assets/Images';
import { Checkbox, Button, InputAdornment, TextField, Typography, IconButton, Snackbar } 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 MuiAlert from '@material-ui/lab/Alert';
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} />);

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);

class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      email: '',
      password: '',
      showPass: false,
      errorEmail: false,
      errorPassword: false,
      msgEmail: '',
      msgPassword: '',
      rememberMe: false,
      alert: false,
      tipeAlert: '',
      messageAlert: '',
      width: 0,
      height: 0,
      maintenanceHeadline: "",
      maintenanceContent: "",
      maintenanceStatus: null,
    }
  }

  componentDidMount() {
    this.getUser()
    var email = localStorage.getItem(Constant.EMAIL)
  }

  getWindowDimensions() {
    const { innerWidth: width, innerHeight: height } = window;
    this.setState({
      width,
      height
    })
  }

  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 Cannot be Empty' })
    } else if (!isEmail) {
      this.setState({ errorEmail: true, msgEmail: 'Please enter a valid email address' })
    } else if (this.state.password.trim() == "") {
      this.setState({ errorPassword: true, msgPassword: 'Password Cannot be Empty' })
    } else {
      this.login()
    }
  }

  closeAlert() {
    this.setState({ alert: false })
  }

  login() {
    let payload = {
      "email": this.state.email,
      "password": this.state.password
    }
    api.create().login(payload).then((response) => {
      console.log(response);
      if (response.data) {
        if (response.ok) {
          if (response.data.status === 'success') {
            // console.log(response.data.data)
            let datas = response.data.data
            if (datas.maintenance_status === 1) {
              this.setState({
                maintenanceHeadline: datas.maintenance_headline,
                maintenanceContent: datas.maintenance_content,
                maintenanceStatus: datas.maintenance_status
              })
            } else {
              localStorage.setItem(Constant.TOKEN, datas.token)
              localStorage.setItem(Constant.USER, datas.user_id)
              localStorage.setItem(Constant.ROLE, datas.role_id)
              if (this.state.rememberMe) {
                localStorage.setItem(Constant.EMAIL, this.state.email)
                localStorage.setItem(Constant.PASSWORD, this.state.password)
                // console.log(this.state.email, this.state.password)
              } else {
                localStorage.setItem(Constant.EMAIL, '')
                localStorage.setItem(Constant.PASSWORD, '')
              }
              this.props.history.push('/home/beranda')
            }

          } else {
            if (response.data.message == 'Password is Not Correct') {
              this.setState({ errorPassword: true, msgPassword: 'Incorrect Password' })
            } else {
              this.setState({ errorEmail: true, msgEmail: response.data.message })
            }
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }
    })
  }

  getUser() {
    var email = localStorage.getItem(Constant.EMAIL)
    var password = localStorage.getItem(Constant.PASSWORD)
    if (email == null || password == null) {
      this.setState({ email: '', password: '' })
    } else if (email != '' && password != '') {
      this.setState({ email, password })
    }
  }


  render() {
    return (
      <div style={{ flex: 1, display: 'flex' }}>
        <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
          <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
            {this.state.messageAlert}
          </Alert>
        </Snackbar>
        <div style={{ width: '50%', display: 'grid' }}>
          <img src={Images.meeting} style={{ objectFit: 'fill', width: '100%', height: '100%' }} />
          {/* <img src={Images.imageLogin} style={{ marginTop: 30 }} /> */}
        </div>
        <div style={{ width: '50%', height: '100vh', backgroundColor: '#263b80', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }}>

          {this.state.maintenanceStatus === 1 ?
            <div>
              <Typography style={{ color: '#fff', fontSize: '2.5rem', margin: '10px 40px' }}>{this.state.maintenanceHeadline}</Typography>
              <div dangerouslySetInnerHTML={{ __html: this.state.maintenanceContent }} style={{ color: '#fff', margin: '10px 40px' }} />
            </div>
            :
            <form onSubmit={(e) => {
              e.preventDefault()
              this.validateLogin()
            }}
            >
              <div style={{ maxWidth: 397, paddingTop: 56, padding: 65, display: 'flex', flexDirection: 'column', height: (this.state.msgEmail.length > 45 ? 485 : 441), borderRadius: 12, boxShadow: '0 2 4 0 rgba(0, 0, 0, 0.2)', backgroundColor: '#ffffff' }}>
                <img src={Images.triputraBlack} style={{ height: 59, width: 175, alignSelf: 'center' }} />

                <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' }}>Password *</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 ? (this.state.msgEmail.length > 45 ? 80 : 35) : 20 }}
                  helperText={this.state.msgPassword}
                  onSubmit={() => this.validateLogin()}
                  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" checked={this.state.rememberMe} onChange={() => this.setState({ rememberMe: !this.state.rememberMe })} />
                  <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' }}>Forgot Password?</span></Link>
                </div>
                <button
                  type="submit"
                  style={{
                    backgroundColor: 'transparent',
                    cursor: 'pointer',
                    borderColor: 'transparent',
                    outline: 'none'
                  }}
                  disabled={this.state.email.trim() == '' && this.state.password.trim() == '' ? true : false}
                // onClick={() => this.validateLogin()}
                >
                  <Button name="submit" variant="contained" disabled={this.state.email.trim() == '' && this.state.password.trim() == '' ? true : false} 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>
                </button>
              </div>
            </form>
          }
        </div>
      </div >
    );
  }
}

export default Login;