Files
tbbank-react-native-mobile/src/screens/Auth/VerificationScreen.js

319 lines
8.1 KiB
JavaScript

import React, { useState, useEffect, useRef } from 'react';
import {
View,
Text,
StyleSheet,
SafeAreaView,
Alert,
TouchableOpacity,
TouchableWithoutFeedback,
Keyboard,
BackHandler,
Platform,
KeyboardAvoidingView,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useFocusEffect } from '@react-navigation/native';
import { useAuth } from '../../contexts/AuthContext';
import Button from '../../components/Button';
import {
CodeField,
Cursor,
useBlurOnFulfill,
useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import { COLORS } from '../../constants/colors';
const CELL_COUNT = 6;
const VerificationScreen = ({ navigation }) => {
const [code, setCode] = useState('');
const [countdown, setCountdown] = useState(60);
const [canResend, setCanResend] = useState(false);
const { verify, isLoading, pendingVerification, clearPendingVerification } = useAuth();
const countdownRef = useRef(null);
const ref = useBlurOnFulfill({ value: code, cellCount: CELL_COUNT });
const [props, getCellOnLayoutHandler] = useClearByFocusCell({
value: code,
setValue: setCode,
});
useEffect(() => {
if (!pendingVerification) {
// If no pending verification, go back to login
navigation.replace('Login');
return;
}
startCountdown();
return () => {
if (countdownRef.current) {
clearInterval(countdownRef.current);
}
};
}, []);
// Handle Android hardware back button
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
handleGoBack();
return true; // Prevent default behavior
};
if (Platform.OS === 'android') {
const sub = BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => sub.remove();
}
}, [handleGoBack])
);
const startCountdown = () => {
setCountdown(60);
setCanResend(false);
countdownRef.current = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
setCanResend(true);
if (countdownRef.current) {
clearInterval(countdownRef.current);
}
return 0;
}
return prev - 1;
});
}, 1000);
};
const handleVerify = async (filledCode) => {
if (!filledCode.trim()) {
Alert.alert('Ýalňyşlyk', 'Tassyklama koduny giriziň');
return;
}
if (!/^\d{6}$/.test(filledCode.trim())) {
Alert.alert('Ýalňyşlyk', 'Tassyklama kody 6 sanly bolmaly');
return;
}
const result = await verify(filledCode.trim());
if (result.success) {
// Navigation will be handled by AuthContext
} else {
Alert.alert('Ýalňyşlyk', result.error);
}
};
const handleVerifyWrapper = () => handleVerify(code);
const handleResendCode = async () => {
if (!canResend) return;
// Here you would call the API to resend the code
// For now, just restart the countdown
Alert.alert('Üstünlik', 'Täze tassyklama kody iberildi');
startCountdown();
};
const handleGoBack = React.useCallback(() => {
clearPendingVerification();
// Check if we can go back, if not navigate to Login
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.navigate('Login');
}
}, [clearPendingVerification, navigation]);
const formatPhoneNumber = (phone) => {
if (!phone) return '';
const phoneStr = phone.toString();
return `+993 ${phoneStr.slice(0, 2)} ${phoneStr.slice(2, 4)}-${phoneStr.slice(4, 6)}-${phoneStr.slice(6)}`;
};
if (!pendingVerification) {
return null; // Will navigate away in useEffect
}
return (
<SafeAreaView style={styles.container}>
<StatusBar style="dark" />
<View style={styles.header}>
<TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
<Text style={styles.backButtonText}> Yza</Text>
</TouchableOpacity>
</View>
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.content}>
<View style={styles.logoContainer}>
<View style={styles.verificationIcon}>
<Text style={styles.verificationIconText}></Text>
</View>
<Text style={styles.title}>Tassyklama</Text>
<Text style={styles.subtitle}>
{formatPhoneNumber(pendingVerification.phone)} belgisine iberilen
6 sanly tassyklama koduny giriziň
</Text>
</View>
<View style={styles.formContainer}>
<CodeField
ref={ref}
{...props}
value={code}
onChangeText={setCode}
cellCount={CELL_COUNT}
rootStyle={styles.otpContainer}
keyboardType="number-pad"
textContentType="oneTimeCode"
renderCell={({ index, symbol, isFocused }) => (
<Text
key={index}
style={[styles.otpInput, isFocused && styles.otpInputHighlight]}
onLayout={getCellOnLayoutHandler(index)}>
{symbol || (isFocused ? <Cursor/> : null)}
</Text>
)}
onSubmitEditing={handleVerifyWrapper}
/>
<Button
title="Tassykla"
onPress={handleVerifyWrapper}
loading={isLoading}
style={styles.verifyButton}
/>
<View style={styles.resendContainer}>
{canResend ? (
<TouchableOpacity onPress={handleResendCode}>
<Text style={styles.resendText}>Kodu gaýtadan iber</Text>
</TouchableOpacity>
) : (
<Text style={styles.countdownText}>
Gaýtadan ibermek üçin {countdown} sekunt garaşyň
</Text>
)}
</View>
</View>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: COLORS.background,
},
header: {
paddingHorizontal: 24,
paddingTop: 16,
},
backButton: {
alignSelf: 'flex-start',
},
backButtonText: {
fontSize: 16,
color: COLORS.primary,
fontWeight: '600',
},
content: {
flex: 1,
paddingHorizontal: 24,
justifyContent: 'center',
},
logoContainer: {
alignItems: 'center',
marginBottom: 48,
},
verificationIcon: {
width: 80,
height: 80,
borderRadius: 40,
backgroundColor: COLORS.success,
alignItems: 'center',
justifyContent: 'center',
marginBottom: 24,
shadowColor: COLORS.success,
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
},
verificationIconText: {
fontSize: 32,
color: COLORS.white,
fontWeight: 'bold',
},
title: {
fontSize: 28,
fontWeight: 'bold',
color: COLORS.textPrimary,
marginBottom: 16,
textAlign: 'center',
},
subtitle: {
fontSize: 16,
color: COLORS.textSecondary,
textAlign: 'center',
lineHeight: 22,
paddingHorizontal: 20,
},
formContainer: {
alignItems: 'center',
},
otpContainer: {
width: '90%',
marginBottom: 32,
},
otpInput: {
width: 45,
height: 60,
lineHeight: 58,
borderWidth: 1,
borderRadius: 12,
borderColor: COLORS.gray[300],
color: COLORS.textPrimary,
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
},
otpInputHighlight: {
borderColor: COLORS.primary,
},
verifyButton: {
width: '100%',
marginBottom: 32,
},
resendContainer: {
alignItems: 'center',
},
resendText: {
fontSize: 16,
color: COLORS.primary,
fontWeight: '600',
},
countdownText: {
fontSize: 14,
color: COLORS.textSecondary,
textAlign: 'center',
},
});
export default VerificationScreen;