import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useRoute } from '@react-navigation/native';
import { Platform, View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../../reducers/contextProvider';
import { customeButtons, customStyles, GetPageTheme } from "../../styles/Global";
import Container from '../../components/container';
import GradientButton from '../../components/gradientButton';
import { notify } from '../../components/notify';
import OtpInputs from 'react-native-otp-inputs';
import LinearGradient from 'react-native-linear-gradient';
import { METHODS, getMethodName } from '../../constants/methodNames';
import { get_item } from '../../components/localStorage';
import CustomLoader from '../../components/CustomLoader';
import { getforgotpasswordotp, verifyotp } from '../../controller/functions';

function VerifyOTP(props) {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkTheme, route.name);
  const customeButton = customeButtons(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);

  const [otp, setOtp] = useState('');
  const [timer, setTimer] = useState(90);
  const [isTimerRunning, setIsTimerRunning] = useState(true);
  const [resendCount, setResendCount] = useState(0);
  const [processing, setProcessing] = useState(false);
  const [resendProcessing, setResendProcessing] = useState(false);

  const [isPINUpdate, setIsPINUpdate] = useState(false);

  const otpRef = useRef();
  const MAX_RESEND_COUNT = 1;

  const username = route?.params?.username;

  useEffect(() => {
    let interval = null;
    if (isTimerRunning) {
      interval = setInterval(() => {
        setTimer((prevTimer) => (prevTimer > 0 ? prevTimer - 1 : 0));
      }, 1000);
    } else if (!isTimerRunning && timer !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isTimerRunning, timer]);

  const handleVerify = () => {
    if (otp.length !== 6) {
      notify('Please enter 6-digit OTP', 'SHORT');
      return;
    }
    Verify_OTP();
  };

  const handleResend = () => {
    if (resendCount < MAX_RESEND_COUNT) {
      setTimer(90);
      setIsTimerRunning(true);
      setResendCount(resendCount + 1);
      resetOTP();
      Resend_OTP();
    }
  };

  const Verify_OTP = async () => {
    setProcessing(true);
    let projectInfo = await get_item('projectInfo');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
    let baseurl = projectDetails.baseURL || '';

    const method_name = getMethodName(METHODS.OTP_VERIFY);
    const url = baseurl + method_name;
    const data = { un: username , otp : otp};
    console.log(url, data)
    await verifyotp(url, data)
      .then(async (res) => {
        setProcessing(false);
        if (res?.Status == true) {
          notify('OTP verify successfully.','SHORT') ;
          resetOTP();
          props?.navigation?.navigate('CreatePassword', {username : username});
        } else if (res?.Status == false) {
          notify(res?.Text,'SHORT') 
        } else if (res.networkErr && res.error) {
          notify('Please connect to internet-' + res.error, 'SHORT');
        } else if (!res.false && res.error) {
          notify(res.error, 'SHORT');
        }

      })
      .catch((err) => {
        setProcessing(false);
        console.log('onPage otp send error1', err);
      });

  }


  const Resend_OTP = async () => {
    setResendProcessing(true);

    let projectInfo = await get_item('projectInfo');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
    let baseurl = projectDetails.baseURL || '';

    const method_name = getMethodName(METHODS.OTP_SEND);
    const url = baseurl + method_name;
    const data = { un: username };
    console.log(url, data)
    await getforgotpasswordotp(url, data)
      .then(async (res) => {
        setResendProcessing(false);
        if (res?.Status == false) {
          notify(res?.Text,'SHORT') // invalid username
        } else if (res?.Status == true) {
          notify("OTP send successfully.",'SHORT')
        } else if (res.networkErr && res.error) {
          notify('Please connect to internet-' + res.error, 'SHORT');
        } else if (!res.false && res.error) {
          notify(res.error, 'SHORT');
        }

      })
      .catch((err) => {
        setResendProcessing(false);
        console.log('onPage otp send error1', err);
      });

  }

  const resetOTP = useCallback(() => {
    otpRef.current.reset();
  }, [])

  async function autosubmit(){ 
    if(otp.trim().length == 6){
      Verify_OTP();
    }
  }

  useEffect(() => {  
    autosubmit();
  }, [isPINUpdate]);

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
      {processing && <CustomLoader title="Verify OTP..." />}
      {resendProcessing && <CustomLoader title="Sending OTP..." />}
      <Image style={styles.performicsLogo} source={require('../../assets/image/PerformicsLogo.png')} />
      
      <View style={styles.infoTextContainer}>
      <Text style={styles.fyourpass}>OTP Verification</Text>
        <Text style={styles.infoText}>One Time password (OTP) has been sent to your registered mobile number.</Text>
      </View>

      <View style={customStyle.mt40}>
        <OtpInputs
          ref={otpRef}
          handleChange={(code) => { setOtp(code); setIsPINUpdate(!isPINUpdate); }}
          numberOfInputs={6}
          secureTextEntry={true}
          defaultValue=''
          keyboardType={"numeric"}
          // autofillFromClipboard={false}
          inputStyles={customStyle.verify_otp_inputStyle}
          style={customStyle.otp_field}
        />
      </View>

      <TouchableOpacity style={styles.resendContainer} onPress={handleResend} disabled={timer > 0 || resendCount >= MAX_RESEND_COUNT} >
        <Text style={styles.resendtop}>Didn't receive the OTP?</Text>
        <Text style={[styles.backtologin, { color: timer > 0 || resendCount >= MAX_RESEND_COUNT ? 'gray' : '#2196F3' }]}>Resend</Text>
      </TouchableOpacity>

      {resendCount >= MAX_RESEND_COUNT && timer === 0 && (
        <Text style={styles.tryLaterText}>Please try after some time.</Text>
      )}

      <Text style={styles.timerText}>{timer > 0 ? `Resend OTP in ${timer}s` : resendCount < MAX_RESEND_COUNT ? 'You can resend the OTP now' : ''}</Text>

      {resendCount >= MAX_RESEND_COUNT && timer === 0 ? 
        <View style={styles.footerView}>
          <TouchableOpacity activeOpacity={1} style={customeButton.g_buttonStyle}>
            <LinearGradient
              colors={['#B2BEB5', '#A9A9A9', '#808080']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
              style={customeButton.g_linearGradient}
            >
              <Text style={customeButton.g_textStyle}>Verify</Text>
            </LinearGradient>
          </TouchableOpacity>
        </View>
        : 
        <View style={[customStyle.footerView]}>
          <GradientButton {...props} title={'Verify'} onPress={handleVerify} />
        </View>
      }

      <TouchableOpacity onPress={() => props.navigation.goBack()}>
        <Text style={styles.backtext}>Back</Text>
      </TouchableOpacity>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(VerifyOTP);

const styles = StyleSheet.create({
  performicsLogo: {
    width: "60%",
    height: "15%",
    resizeMode: 'contain',
    marginTop: 40
  },
  backtologin: {
    fontSize: 17,
    textDecorationLine: 'underline'
  },
  resendtop: {
    fontSize: 15,
    marginRight: 5
  },
  fyourpass: {
   color:'#000000', fontSize: 22,
  fontWeight: '400',
  paddingHorizontal: 30,
  },
  resendContainer: {
    width: '90%',
    height: '7%',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    borderRadius: 5,
  },
  infoTextContainer: {
    alignItems: 'flex-start',
    alignSelf: 'flex-start',
    alignContent: 'flex-start'
  },
  infoText: {
    paddingHorizontal: 30,
    marginTop: 20,
    fontSize: 16
  },
  tryLaterText: {
    textAlign: 'center',
    marginTop: 10,
    color: 'red',
    fontSize: 16
  },
  timerText: {
    textAlign: 'center'
  },
  backtext: {
    color: '#2196F3',
    fontSize: 17,
    marginTop: 10,
    textAlign: 'center'
  },
});
