import React, { useState, useEffect } from 'react'; import { View, Text, TouchableOpacity, KeyboardAvoidingView, Platform, } from 'react-native'; import { useNavigation, useRoute, RouteProp } from '@react-navigation/native'; import { StackNavigationProp } from '@react-navigation/stack'; import { getStyles } from './otpScreen.styles'; import { PrimaryButton } from '@components'; import { useAppTheme } from '@theme'; import { useAppDispatch } from '../../../store'; import { verifyOtp } from '../../../store/commonreducers/auth'; import { AuthStackParamList } from '../../../navigation/authStack'; type OtpNavProp = StackNavigationProp; type OtpRouteProp = RouteProp; const OTP_LENGTH = 6; const RESEND_TIMER = 30; export const OtpScreen: React.FC = () => { const { colors } = useAppTheme(); const styles = getStyles(colors); const navigation = useNavigation(); const route = useRoute(); const dispatch = useAppDispatch(); const { mobileNumber } = route.params; const [otp, setOtp] = useState(Array(OTP_LENGTH).fill('')); const [activeIndex, setActiveIndex] = useState(0); const [timer, setTimer] = useState(RESEND_TIMER); const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (timer > 0) { const interval = setInterval(() => setTimer((t) => t - 1), 1000); return () => clearInterval(interval); } }, [timer]); const handleKeyPress = (key: string) => { if (key === 'backspace') { if (otp[activeIndex] || activeIndex > 0) { const newOtp = [...otp]; if (otp[activeIndex]) { newOtp[activeIndex] = ''; } else if (activeIndex > 0) { newOtp[activeIndex - 1] = ''; setActiveIndex(activeIndex - 1); } setOtp(newOtp); } } else if (key >= '0' && key <= '9' && activeIndex < OTP_LENGTH) { const newOtp = [...otp]; newOtp[activeIndex] = key; setOtp(newOtp); if (activeIndex < OTP_LENGTH - 1) { setActiveIndex(activeIndex + 1); } } }; const handleVerify = async () => { const otpString = otp.join(''); if (otpString.length !== OTP_LENGTH) return; setIsLoading(true); await dispatch(verifyOtp({ mobileNumber, otp: otpString })); setIsLoading(false); navigation.navigate('SetLocationScreen'); }; return ( Verify OTP Code sent to {mobileNumber} {otp.map((digit, index) => ( {digit} ))} {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((num) => ( handleKeyPress(String(num))} activeOpacity={0.6} > {num} ))} handleKeyPress('backspace')} activeOpacity={0.6} > handleKeyPress('0')} activeOpacity={0.6} > 0 {timer > 0 ? ( Resend code in {timer}s ) : ( { setTimer(RESEND_TIMER); setOtp(Array(OTP_LENGTH).fill('')); setActiveIndex(0); }} activeOpacity={0.7} > Resend OTP )} ); };