This commit is contained in:
Abin Toppo
2025-09-29 16:32:39 +05:30
parent a624af60b7
commit 7a9ce601cb
12 changed files with 773 additions and 617 deletions
+190 -167
View File
@@ -13,41 +13,54 @@ import {
TextInputKeyPressEventData,
KeyboardAvoidingView,
StatusBar,
Alert,
ToastAndroid,
} from "react-native";
import { RootStackParamList } from "../navigation/AppNavigator";
import * as Keychain from "react-native-keychain";
import { BASE_URL, LOGIN_URL, VARIFY_OTP_URL } from "../utils/ApiUrls";
import { LOGIN_URL, VARIFY_OTP_URL } from "../utils/ApiUrls";
import colors from "../components/colors";
import { fetchUserProfile } from "../utils/HelperFunction";
const theme = {
primary: "#111111",
accent: colors.primary,
background: "#F9F9F9",
text: "#1A1A1A",
subText: "#6B6B6B",
outline: "#E5E5E5",
};
import LinearGradient from "react-native-linear-gradient";
import CustomAlert from "../components/CostomAlart";
const CELL_COUNT = 6;
type OtpVerifyRouteProp = RouteProp<RootStackParamList, "OtpVarify">;
interface AlertButton {
text: string;
onPress: () => void;
style?: "cancel" | "destructive" | "default";
}
export default function OtpVerificationScreen() {
const [code, setCode] = useState<string[]>(Array(CELL_COUNT).fill(""));
const [timer, setTimer] = useState(30);
const [isResending, setIsResending] = useState(false);
const [alertConfig, setAlertConfig] = useState<{
visible: boolean;
title: string;
message: string;
buttons: AlertButton[];
alertType: 'error' | 'success' | 'info';
}>({
visible: false,
title: "",
message: "",
buttons: [],
alertType: "info",
});
const inputs = useRef<Array<TextInput | null>>([]);
const route = useRoute<OtpVerifyRouteProp>();
const { mobile } = route.params;
const navigation = useNavigation<any>();
// animations
// Refs for auto-closing logic
const successActionRef = useRef<(() => void) | null>(null);
const successTimerRef = useRef<number | null>(null);
const fade = useRef(new Animated.Value(0)).current;
const slide = useRef(new Animated.Value(24)).current;
const ctaScale = useRef(new Animated.Value(1)).current;
useEffect(() => {
Animated.parallel([
Animated.timing(fade, { toValue: 1, duration: 600, useNativeDriver: true }),
@@ -55,88 +68,133 @@ export default function OtpVerificationScreen() {
]).start();
}, [fade, slide]);
// Countdown
useEffect(() => {
if (timer <= 0) return;
const interval = setInterval(() => {
setTimer((prev) => prev - 1);
}, 1000);
const interval = setInterval(() => setTimer((prev) => prev - 1), 1000);
return () => clearInterval(interval);
}, [timer]);
const hideAlert = () => {
if (successTimerRef.current) {
clearTimeout(successTimerRef.current);
successTimerRef.current = null;
}
setAlertConfig(prev => ({ ...prev, visible: false }));
};
const triggerAlert = (
title: string,
message: string,
buttons: AlertButton[],
alertType: 'error' | 'success' | 'info' = 'info',
autoCloseAction?: () => void
) => {
setAlertConfig({ visible: true, title, message, buttons, alertType });
if (alertType === 'success' && autoCloseAction) {
successActionRef.current = autoCloseAction;
successTimerRef.current = setTimeout(() => {
successActionRef.current?.();
}, 2000); // Auto-close after 2 seconds
}
};
const saveToken = async (token: string) => {
try {
await Keychain.setGenericPassword("auth", token, {
accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED,
});
await Keychain.setGenericPassword("auth", token, { accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED });
console.log("✅ Token saved securely");
} catch (error) {
console.error("❌ Error saving token:", error);
}
};
const onSubmit = async (otp: string, mobile: string) => {
try {
const payload = { mobile, otp };
const res = await axios.post(
VARIFY_OTP_URL,
payload,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
console.log("✅ OTP Verified:", res.data);
if (res.data?.statusCode === 200) {
const { jwt, role } = res.data?.data || {};
saveToken(jwt);
navigation.navigate("Home");
ToastAndroid.show("OTP Verified Successfully!", ToastAndroid.SHORT);
if (otp.length !== CELL_COUNT) {
triggerAlert(
'Incomplete Code',
'Please enter all 6 digits of the OTP.',
[{ text: 'OK', onPress: hideAlert }],
'error'
);
return;
}
} catch (err: any) {
console.error("❌ OTP Verification Error:", err?.response?.data || err.message);
ToastAndroid.show(
err?.response?.data?.message || "Invalid OTP. Please try again.",
ToastAndroid.SHORT
);
}
};
try {
const res = await axios.post(VARIFY_OTP_URL, { mobile, otp }, {
headers: { "Content-Type": "application/json", Accept: "application/json" },
});
if (res.data?.statusCode === 200) {
const { jwt } = res.data?.data || {};
await saveToken(jwt);
let hasActionRun = false;
const successAction = () => {
if (hasActionRun) return;
hasActionRun = true;
hideAlert();
navigation.navigate("Home");
};
triggerAlert(
'Success!',
'OTP verified successfully. Redirecting...',
[{ text: 'OK', onPress: successAction }],
'success',
successAction
);
}
} catch (err: any) {
console.error("❌ OTP Verification Error:", err?.response?.data || err.message);
triggerAlert(
'Verification Failed',
err?.response?.data?.message || "Invalid OTP. Please try again.",
[{ text: 'Try Again', onPress: hideAlert, style: 'cancel' }],
'error'
);
}
};
const resendOtp = async () => {
try {
setIsResending(true);
setTimer(30); // reset timer
const res = await axios.get(
LOGIN_URL + mobile,
{ headers: { "Content-Type": "application/json", Accept: "*/*" } }
);
console.log("📩 OTP Resent:", res);
setTimer(30);
await axios.get(`${LOGIN_URL}?mobile=${mobile}`, {
headers: { "Content-Type": "application/json", Accept: "*/*" },
});
setCode(Array(CELL_COUNT).fill(""));
inputs.current[0]?.focus();
ToastAndroid.show("OTP Sent", ToastAndroid.SHORT);
let hasActionRun = false;
const successAction = () => {
if (hasActionRun) return;
hasActionRun = true;
hideAlert();
};
triggerAlert(
'OTP Sent',
'A new code has been sent to your mobile number.',
[{ text: 'OK', onPress: successAction }],
'success',
successAction
);
} catch (err: any) {
console.error("❌ Resend OTP Error:", err?.response?.data || err.message);
ToastAndroid.show("Failed to resend OTP. Try again later.", ToastAndroid.SHORT);
triggerAlert(
'Error',
'Failed to resend OTP. Try again later.',
[{ text: 'OK', onPress: hideAlert, style: 'cancel' }],
'error'
);
} finally {
setIsResending(false);
}
};
const submitIfComplete = (arr: string[]) => {
const joined = arr.join("");
if (joined.length === CELL_COUNT) {
onSubmit(joined, mobile);
if (arr.join("").length === CELL_COUNT) {
onSubmit(arr.join(""), mobile);
}
};
@@ -155,13 +213,14 @@ export default function OtpVerificationScreen() {
updateIndex(0, digits);
return;
}
const next = Array(CELL_COUNT)
.fill("")
.map((_, i) => digits[i] ?? "");
const next = Array(CELL_COUNT).fill("").map((_, i) => digits[i] ?? "");
setCode(next);
const firstEmpty = next.findIndex((c) => !c);
if (firstEmpty >= 0) inputs.current[firstEmpty]?.focus();
else inputs.current[CELL_COUNT - 1]?.blur();
if (firstEmpty >= 0) {
inputs.current[firstEmpty]?.focus();
} else {
inputs.current[CELL_COUNT - 1]?.blur();
}
submitIfComplete(next);
};
@@ -172,107 +231,71 @@ export default function OtpVerificationScreen() {
};
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === "ios" ? "padding" : undefined}
>
<StatusBar barStyle="dark-content" backgroundColor={theme.background} />
<LinearGradient colors={[colors.pastelGreen, colors.pastelOrange]} style={styles.gradientContainer}>
<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === "ios" ? "padding" : undefined}>
<StatusBar barStyle="dark-content" backgroundColor={colors.pastelGreen} />
<CustomAlert {...alertConfig} />
{/* Top Section */}
<View style={styles.topSection}>
<Text style={styles.title}>Verify Code 🔒</Text>
<Text style={styles.subtitle}>
We’ve sent a 6-digit verification code to {mobile}.
</Text>
<View style={styles.topSection}>
<Text style={styles.title}>Verify Your Code 🔒</Text>
<Text style={styles.subtitle}>We’ve sent a 6-digit verification code to +91 {mobile}.</Text>
<Animated.View
style={[styles.otpRow, { opacity: fade, transform: [{ translateY: slide }] }]}
>
{Array.from({ length: CELL_COUNT }).map((_, i) => (
<TextInput
key={`otp-${i}`}
ref={(r) => {
inputs.current[i] = r;
}}
style={[styles.cell, code[i] ? styles.cellFilled : null]}
keyboardType="number-pad"
maxLength={1}
value={code[i]}
onChangeText={(t) => (i === 0 ? handleFirstCellChange(t) : updateIndex(i, t))}
onKeyPress={(e) => handleKeyPress(i, e)}
placeholder="•"
placeholderTextColor="#BDBDBD"
textContentType="oneTimeCode"
/>
))}
</Animated.View>
</View>
<Animated.View style={[styles.otpRow, { opacity: fade, transform: [{ translateY: slide }] }]}>
{Array.from({ length: CELL_COUNT }).map((_, i) => (
<TextInput
key={`otp-${i}`}
ref={(r) => { inputs.current[i] = r; }}
style={[styles.cell, code[i] ? styles.cellFilled : null]}
keyboardType="number-pad"
maxLength={i === 0 ? CELL_COUNT : 1}
value={code[i]}
onChangeText={(t) => (i === 0 ? handleFirstCellChange(t) : updateIndex(i, t))}
onKeyPress={(e) => handleKeyPress(i, e)}
placeholder="•"
placeholderTextColor="#BDBDBD"
textContentType="oneTimeCode"
/>
))}
</Animated.View>
</View>
{/* Bottom Section */}
<Animated.View style={[styles.bottomSection, { transform: [{ scale: ctaScale }] }]}>
<Pressable
onPressIn={() =>
Animated.spring(ctaScale, { toValue: 0.97, useNativeDriver: true }).start()
}
onPressOut={() =>
Animated.spring(ctaScale, { toValue: 1, useNativeDriver: true }).start()
}
onPress={() => onSubmit(code.join(""), mobile)}
style={styles.button}
>
<Text style={styles.buttonText}>Continue</Text>
</Pressable>
{timer > 0 ? (
<Text style={styles.footerText}>Resend code in 00:{timer.toString().padStart(2, "0")}</Text>
) : (
<Pressable onPress={resendOtp} disabled={isResending}>
<Text style={[styles.footerText, { color: theme.accent }]}>
{isResending ? "Resending..." : "Resend Code"}
</Text>
<Animated.View style={[styles.bottomSection, { transform: [{ scale: ctaScale }] }]}>
<Pressable
onPressIn={() => Animated.spring(ctaScale, { toValue: 0.97, useNativeDriver: true }).start()}
onPressOut={() => Animated.spring(ctaScale, { toValue: 1, useNativeDriver: true }).start()}
onPress={() => onSubmit(code.join(""), mobile)}
style={styles.button}
>
<Text style={styles.buttonText}>Verify & Continue</Text>
</Pressable>
)}
</Animated.View>
</KeyboardAvoidingView>
{timer > 0 ? (
<Text style={styles.footerText}>Resend code in 00:{timer.toString().padStart(2, "0")}</Text>
) : (
<Pressable onPress={resendOtp} disabled={isResending}>
<Text style={[styles.footerText, { color: colors.primary, fontWeight: '600' }]}>
{isResending ? "Resending..." : "Resend Code"}
</Text>
</Pressable>
)}
</Animated.View>
</KeyboardAvoidingView>
</LinearGradient>
);
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: theme.background, padding: 20 },
topSection: { flex: 1, justifyContent: "center" },
title: { fontSize: 26, fontWeight: "800", color: theme.text, marginBottom: 8 },
subtitle: {
fontSize: 15,
color: theme.subText,
marginBottom: 24,
lineHeight: 22,
},
otpRow: { flexDirection: "row", justifyContent: "space-between" },
cell: {
width: 50,
height: 58,
borderRadius: 12,
borderWidth: 1,
borderColor: theme.outline,
backgroundColor: "#fff",
textAlign: "center",
fontSize: 20,
color: theme.text,
},
cellFilled: { borderColor: "#D1D1D1" },
bottomSection: { marginBottom: 30 },
button: {
backgroundColor: colors.primary,
paddingVertical: 18,
borderRadius: 14,
alignItems: "center",
justifyContent: "center",
},
buttonText: { color: "#000", fontWeight: "700", fontSize: 16 },
footerText: {
textAlign: "center",
color: theme.subText,
fontSize: 13,
marginTop: 14,
},
gradientContainer: { flex: 1 },
container: { flex: 1, padding: 24, justifyContent: "space-between" },
topSection: { flex: 1, justifyContent: "center", alignItems: 'center' },
title: { fontSize: 28, fontWeight: "bold", color: colors.textDark, textAlign: 'center', marginBottom: 12 },
subtitle: { fontSize: 16, color: colors.textLight, textAlign: 'center', marginBottom: 32, lineHeight: 24, maxWidth: 300 },
otpRow: { flexDirection: "row", justifyContent: "space-between", width: '100%', paddingHorizontal: 10 },
cell: { width: 48, height: 56, borderRadius: 12, borderWidth: 1.5, borderColor: colors.inputBorder, backgroundColor: colors.white, textAlign: "center", fontSize: 22, fontWeight: '700', color: colors.textDark, shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.08, shadowRadius: 8, elevation: 3 },
cellFilled: { borderColor: colors.primary, backgroundColor: '#F7F2FF' },
bottomSection: { paddingBottom: Platform.OS === "ios" ? 20 : 10 },
button: { backgroundColor: colors.primary, paddingVertical: 18, borderRadius: 30, alignItems: "center", justifyContent: "center", shadowColor: colors.primary, shadowOffset: { width: 0, height: 8 }, shadowOpacity: 0.3, shadowRadius: 15, elevation: 8 },
buttonText: { color: colors.white, fontWeight: "700", fontSize: 16 },
footerText: { textAlign: "center", color: colors.textLight, fontSize: 14, marginTop: 20 },
});