import React from 'react';
import withStyles from "@material-ui/core/styles/withStyles";
import {styles} from './style';

import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import Button from '@material-ui/core/Button';
import Hidden from '@material-ui/core/Hidden';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import InputAdornment from '@material-ui/core/InputAdornment';
import IconButton from '@material-ui/core/IconButton';
import CircularProgress from '@material-ui/core/CircularProgress';
import Snackbar from '@material-ui/core/Snackbar';
import Text from 'material-ui/TextField';

import moment from 'moment';
import { Link } from 'react-router-dom';
import {inject, observer} from 'mobx-react';
import {LINKS} from "../../routes";

@inject('appstate')
@observer
class OtpPage extends React.Component{
    otp = [];
    urlParams = new URLSearchParams(window.location.search);

    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
          email: "",
          password: "",
          showPassword : false,
          isLoading: false,
          loginFailed: false,
          isNeedEmailVerification: false,
          otp: [],
          otpText : "",
          otpData : {},
          isResending: false,
          isOtpExpired : false,
          isOtpWrong: false,
        };
        this.defaultState = Object.assign({}, this.state);
        this.authStore = props.appstate.auth;
      }

    componentDidMount(){
        this.otp[0].focus();
        if(this.urlParams.has('login_request_id') && this.urlParams.has('expired_at')) {
            console.log(this.urlParams);
            this.setState({
                otpData:{
                    login_request_id : this.urlParams.get('login_request_id'),
                    expired_at : this.urlParams.get('expired_at')
                }
            });
        }
        else{
            this.setState({otpData:this.authStore.otpData});
        }
    }

    checkIsExpired(){
        console.log(Date.parse(Date().toISOString()),this.state.otpData.expired_at);
        if(Date.parse(Date().toISOString()) < Date.parse(this.state.otpData.expired_at)){
            return false;
        }else{
            return true
        }
    }

    handleChange = name => event => {
        this.setState({
            [name]: event.target.value,
        });
    };

    resendCode = () => {
        this.setState({isResending:true});
        setTimeout(()=>{
            this.setState({isResending:false});
        },3000);
    }

    login = () => {
        let data = {
            code : this.state.otpText,
            login_request_id : this.state.otpData.login_request_id
        }
        console.log("data",data);
        this.setState({isLoading:true});
        // if(this.checkIsExpired){
        //     this.setState({isOtpExpired:true});
        //     setTimeout(()=>{
        //         this.setState({isOtpExpired:false});
        //     },2000);
        // }
        // else{
            this.authStore.validateOtp(data).then(res=>{
                setTimeout(()=>{
                    this.props.history.push(LINKS.DASHBOARD);
                    this.setState({isLoading:false});
                },1000);
            }).catch(err=>{
                setTimeout(()=>{
                    this.setState({isLoading:false,isOtpWrong:true});
                },2000);
                setTimeout(()=>{
                    this.setState({isOtpWrong:false});
                },4000)
            });
        // }

    };

    render(){
        const { classes } = this.props;
        return (
            <div className={classes.container}>
                <Snackbar
                    anchorOrigin={{ vertical : 'top', horizontal: 'center' }}
                    open={this.state.isOtpWrong}
                    onClose={()=>this.setState({isOtpWrong:false})}
                    ContentProps={{
                        'aria-describedby': 'message-id',
                    }}
                    message={<span id="message-id">Wrong OTP code</span>}
                />
                <Snackbar
                    anchorOrigin={{ vertical : 'top', horizontal: 'center' }}
                    open={this.state.isOtpExpired}
                    onClose={()=>this.setState({isOtpExpired:false})}
                    ContentProps={{
                        'aria-describedby': 'message-id',
                    }}
                    message={<span id="message-id">Your OTP code has expired</span>}
                />
                <Snackbar
                    anchorOrigin={{ vertical : 'top', horizontal: 'center' }}
                    open={this.state.isResending}
                    onClose={()=>this.setState({isResending:false})}
                    ContentProps={{
                        'aria-describedby': 'message-id',
                    }}
                    message={<span id="message-id">OTP Code Re-sended</span>}
                />
                <Grid container spacing={0} className={classes.gridContainer}>
                    <Grid item xs={12} className={classes.logoContainer}>
                        <img src={require('../../../../assets/images/login/logo_new.png')} className={classes.logo} />
                    </Grid>
                    <Grid item xs={12} sm={12} md={10} lg={6} className={classes.registerContainer}>
                        <Grid container spacing={24} className={classes.registerPaper}>
                            {/* <Hidden smDown>
                                <Grid item xs={6}>
                                    <img src={require('../../../../assets/images/login/register_image_2.png')} width={"80%"}/>
                                    <Typography style={{color : '#FFF'}} variant={"h6"}>
                                        Welcome to BTN Points
                                    </Typography>
                                    <Typography style={{color : '#FFF'}} variant={"subtitle2"}>
                                        Sign in to get various voucher and items
                                    </Typography>
                                </Grid>
                            </Hidden> */}
                            <Grid item xs={12} sm={12} md={6} style={{paddingLeft : 50,paddingRight : 50}}>
                                <Paper className={classes.formRegister}>
                                    <Typography variant="h6" gutterBottom>
                                        Input Your OTP Code
                                    </Typography>
                                    <Typography variant="subtitle2" gutterBottom>
                                        Still not received OTP Code? <a onClick={()=>this.resendCode()}>Resend Code</a>
                                    </Typography>
                                    <Grid container justify="center" spacing={8}>
                                        {[0, 1, 2, 3, 4, 5].map(x => (
                                        <Grid item xs={1}>
                                            <Text onChange={event=>this.setState({otpText:this.state.otpText+event.target.value})} autoFocus={true} ref={(input) => { this.otp[x] = input; }} key={x} id={x} inputStyle={{textAlign:'center'}} style={{width:'100%'}} type="tel" maxLength="1"/>
                                        </Grid>
                                        ))}
                                    </Grid>
                                    <div style={{padding : 5,marginTop : 20}}>
                                        <Button onClick={() => this.login()} fullWidth variant="contained" style={{background:'#ffeb3b'}} disabled={this.state.otpText.length < 6}>
                                            {this.state.isLoading ? <CircularProgress className={classes.progress} /> : "Sign In"}
                                        </Button>
                                    </div>
                                </Paper>
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>
            </div>
        )
    }
}

export default withStyles(styles)(OtpPage);
