import React, { Component } from 'react';
import Images from '../assets/Images';
import { TextField, InputAdornment, Button, Typography, Snackbar } from '@material-ui/core';
import api from '../api';
import Constant from '../library/Constant';
import MuiAlert from '@material-ui/lab/Alert';
import { withStyles } from '@material-ui/core/styles';

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

class ForgotPassword extends Component {
    constructor(props) {
        super(props)
        this.state = {
            email: '',
            errorEmail: false,
            msgEmail: '',
            alert: false,
            tipeAlert: '',
            messageAlert: ''  
        }
    }

    componentDidMount(){
        console.log("forgot-password")
    }

    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: '' })
      }
    }

    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());
    }

    validateEmail() {
        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 {
          this.verification()
      }
  }

    verification() {
      // alert('test')
      let payload = {
        "email": this.state.email
      }
      api.create().verification(payload).then((response) => {
        if (response.data) {
            if (response.ok) {
                if(response.data.status === 'success') {
                    this.props.history.push('/email-verification')
                } 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' }) 
        }
      })
    }

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

    render() {
        return (
          <div style={{ flex: 1, display: 'flex', backgroundColor: '#263b80', height: '100vh', justifyContent: 'center', alignItems: 'center' }}>
            <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={{padding: 60, display: 'flex', flexDirection: 'column', width: (this.state.msgEmail.length > 45 ? 423 : 378), height: 351, borderRadius: 12, boxShadow: '0 2 4 0 rgba(0, 0, 0, 0.2)', backgroundColor: '#ffffff', justifyContent: 'center', alignItems: 'center' }}>
              <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={"email"}
                    name={"email"}
                    value={this.state.email}
                    onChange={(email) => {
                      this.handleChange(email)
                    }}
                    variant="outlined"
                    error={this.state.errorEmail}
                    style={{ width: 250, height: 51, marginTop: 32, fontSize: 14 }}
                    helperText={this.state.msgEmail}
                    InputProps={{
                        endAdornment: <InputAdornment position="end"><img src={Images.email} /></InputAdornment>,
                    }}
                />

                <Button name="submit" variant="contained" disabled={this.state.email.trim() === '' ? true : false} onClick={() => this.validateEmail()} style={{ marginTop: this.state.errorEmail ? (this.state.msgEmail.length > 45 ? 80 : 35) : 23,  width: '100%', height: 30, borderRadius: 4, color: this.state.email.trim() === '' ? '#4b4b4b' : '#fff', backgroundColor: this.state.email.trim() === '' ? '#d8d8d8' : '#51c6ea' }}>
                  <Typography style={{fontSize: 12, fontFamily: 'Nunito Sans, sans-serif'}}>Reset Password</Typography>
                </Button>

                <div style={{ marginTop: 24}}>
                  <span onClick={() => this.props.history.goBack()} style={{ color: '#51c6ea', cursor: 'pointer' }}>
                    <Typography style={{fontSize: 14}}>Back To Login</Typography>
                  </span>
                </div>
              </div>
          </div>
        );
      }
}

export default ForgotPassword;