import React, {Component} from 'react';
import { Alert, KeyboardAvoidingView, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { BackgroundImage } from '../../components/BackgroundImage';
import { CustomInput } from '../../components/CustomInput';
import { t } from '../../utils/i18n';
import IndicatorLoading from '../../components/IndicatorLoading';
import { sendVerifyOTP, forgetPassword } from '../../api/UserApi';

class VerifyOTP extends Component {
  constructor(props) {
    super(props)
    this.state = {
      otp: null,
      is_loading: false,
      seconds: 300000,
      minuteLeft: 5,
      secondLeft: 0,
      token: this.props.navigation.getParam('token', null),
      mobile: this.props.navigation.getParam('mobile', null)
    }

    this.countdownTimer = null
  }

  componentDidMount () {
    this.startTimer()
  }

  componentWillUnmount () {
    this.countdownTimer = null
  }

  startTimer = () => {
    if (this.countdownTimer) return; 

    this.countdownTimer = setInterval(() => {

      if(this.state.seconds > 0) {
        this.setState({ 
          seconds: this.state.seconds - 1000
        }, () => {
          let min = parseInt(this.state.seconds/60000)
          this.setState({
            minuteLeft: min
          })

          let min_to_ms = min * 60000
          let sec = parseInt((this.state.seconds - min_to_ms)/1000)
          this.setState({
            secondLeft: sec 
          })
        })
      }else {
        clearInterval(this.interval);
        this.countdownTimer = null;
      }
    }, 1000);
  };

  submitVerifyOTP = () => {
    this.setState({
      is_loading: true
    }, async () => {
      await sendVerifyOTP(this.state.token, this.state.otp).then(res => {
        if(res && res.data && res.data.success) {
          this.setState({
            is_loading: false
          }, () => {
            this.props.navigation.navigate('PasswordCode', {password: res.data.password})
          })
        }else {
          let message = res && res.data && res.data.message ? res.data.message : ''
          Alert.alert(t('unsuccessful'), message)
          this.setState({
          is_loading: false
          })
        }
       })
    })
    
  }

  resentRequestOTP = async () => {
    this.setState({
      is_loading: true
    }, () => {
      forgetPassword(this.state.mobile)
        .then(res => {
          if(res.data && res.data.success){
            Alert.alert(t('success'), t('check_otp_msg'), [
              {
                text: 'OK',
                  onPress: () => {
                  this.setState({
                    is_loading: false,
                    seconds: 300000,
                    minuteLeft: 5,
                    secondLeft: 0,
                  }, () => {
                    this.startTimer()
                  })
                }
              }
            ])
          }else {
            let message = res && res.data && res.data.message ? res.data.message : '';
            Alert.alert(t('unsuccessful'), message)
            this.setState({
              is_loading: false
            })
          }
        })
    })
  }

  render() {
    return (
      <SafeAreaView style={{flex: 1}}>
        <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
          flex: 1,
          width: null,
          height: null,
          resizeMode: 'cover'
        }}>
          <BackgroundImage>
            <KeyboardAvoidingView style={{flex:1}}
              keyboardVerticalOffset={Platform.OS == 'ios' ? 70 : 0} 
              behavior={Platform.OS == 'ios' ? "padding" : ""} enabled>
                <View style={styles.container}>
                  <View style={{flex: 0.7, flexDirection: 'column', alignItems: 'center', justifyContent: 'center'}}>
                    <Text style={[styles.fontPromtBold, {color: 'white', fontSize: 30}]}>{t('verify_otp')}</Text>
                    <Text style={[styles.fontPromtRegular, {color: 'white', fontSize: 18, textAlign: 'center'}]}>{t('enter_otp')}</Text>
                    <Text style={[styles.fontPromtRegular, {color: 'white', fontSize: 18, marginBottom: 50, textAlign: 'center'}]}>{t('to_phone_number')} {this.state.mobile}</Text>

                    <CustomInput
                      onChangeText={(e) => {
                        this.setState({
                          otp: e
                        })
                      }}
                      inputTextAlign={'center'}
                      placeholder={'XXXX'}
                      placeholderTextColor={'#FFFFFF40'}
                      keyboardType='numeric'
                      maxLength={4}
                      textInputStyles={{fontSize: 20}}
                      style={[styles.form_input]} />


                    {
                      this.state.minuteLeft > 0 || this.state.secondLeft > 0 ?
                        <Text style={[styles.fontPromtRegular, {color: 'white', marginTop: 30, fontSize: 17}]}>
                            {t('resend_otp')} {this.state.minuteLeft >= 10 ? this.state.minuteLeft : '0' + this.state.minuteLeft}:
                            {this.state.secondLeft >= 10 ? this.state.secondLeft : '0' + this.state.secondLeft} {t('minutes')}
                        </Text>
                      :
                        <TouchableOpacity style={{marginTop: 30}} onPress={this.resentRequestOTP}>
                          <Text style={[styles.fontPromtRegular, {color: 'white', fontSize: 17}]}>{t('resend_code')}</Text>
                        </TouchableOpacity>
                        
                    }
                  
                  </View>

                  <View style={{flex: 0.3, marginTop: 20}}>
                    <TouchableOpacity onPress={this.submitVerifyOTP} 
                                      disabled={this.state.otp === null || this.state.otp === ''}
                                      style={styles.btnSubmit}>
                      <Text style={styles.textBtnSubmit}>
                        {t('confirm')}
                      </Text>
                    </TouchableOpacity>
                  </View>
              </View>
            </KeyboardAvoidingView>
          </BackgroundImage>

          <IndicatorLoading loadingVisible={this.state.is_loading}/>
        </LinearGradient>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1, 
    justifyContent: 'center',
    alignItems: 'center', 
    padding: 40
  },
  fontPromtBold: {
    fontFamily: 'Prompt-Bold'
  },
  fontPromtRegular: {
    fontFamily: 'Prompt-Regular'
  },
  form_input: {
    backgroundColor: 'rgba(0,0,0,0)',
    borderColor: 'white',
    borderRadius: 30,
    borderWidth: 1,
    width: '50%'
  },
  btnSubmit: {
    marginTop: 35,
    backgroundColor: 'white',
    borderRadius: 30,
    paddingVertical: 10,
    paddingHorizontal: 50,
  },
  textBtnSubmit: {
    color: '#2470A1',
    fontFamily: 'Prompt-Bold',
    fontSize: 16,
    textAlign: 'center'
  }
})

export default VerifyOTP