acupedia-mobile-ui/src/app/login/forgot-password.tsx

312 lines
9.6 KiB
TypeScript

import React, { useState } from "react";
import {
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Text,
View,
Alert,
Pressable,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { AuthColors } from "@/features/auth/constants/colors";
import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import FieldLabel from "@/components/forms/FieldLabel";
import { forgotPassword, resetPassword } from "@/features/auth/api/auth.api";
export default function ForgotPasswordScreen() {
const [step, setStep] = useState<"request" | "verify">("request");
const [email, setEmail] = useState("");
const [otpCode, setOtpCode] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [emailError, setEmailError] = useState("");
const [otpError, setOtpError] = useState("");
const [passwordError, setPasswordError] = useState("");
const [confirmError, setConfirmError] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleRequestOtp = async () => {
setEmailError("");
const cleanEmail = email.trim().toLowerCase();
if (!cleanEmail) {
setEmailError("Email is required");
return;
}
if (!/\S+@\S+\.\S+/.test(cleanEmail)) {
setEmailError("Please enter a valid email address");
return;
}
setIsLoading(true);
try {
const res = await forgotPassword({ email: cleanEmail });
const msg = res.message || "Verification code sent! Check your inbox.";
if (Platform.OS === "web") {
window.alert(msg);
} else {
Alert.alert("Code Sent", msg);
}
setStep("verify");
} catch (err: any) {
const errMsg = err?.response?.data?.detail || "Failed to send verification code.";
setEmailError(errMsg);
} finally {
setIsLoading(false);
}
};
const handleResetPassword = async () => {
setOtpError("");
setPasswordError("");
setConfirmError("");
let hasError = false;
if (!otpCode.trim() || otpCode.trim().length !== 6) {
setOtpError("Please enter the 6-digit code");
hasError = true;
}
if (!newPassword) {
setPasswordError("New password is required");
hasError = true;
} else if (newPassword.length < 8) {
setPasswordError("Must be at least 8 characters");
hasError = true;
} else if (/\s/.test(newPassword)) {
setPasswordError("Password must not contain spaces");
hasError = true;
} else if (!/[A-Z]/.test(newPassword)) {
setPasswordError("Must contain at least one uppercase letter");
hasError = true;
} else if (!/[0-9]/.test(newPassword)) {
setPasswordError("Must contain at least one number");
hasError = true;
} else if (!/[^A-Za-z0-9\s]/.test(newPassword)) {
setPasswordError("Must contain at least one special character");
hasError = true;
}
if (!confirmPassword) {
setConfirmError("Please confirm your password");
hasError = true;
} else if (newPassword !== confirmPassword) {
setConfirmError("Passwords do not match");
hasError = true;
}
if (hasError) return;
setIsLoading(true);
try {
const res = await resetPassword({
email: email.trim().toLowerCase(),
otp_code: otpCode.trim(),
new_password: newPassword,
});
const successMsg = res.message || "Password reset successfully! You can now log in.";
if (Platform.OS === "web") {
window.alert(successMsg);
router.replace("/login");
} else {
Alert.alert("Success", successMsg, [
{ text: "Log In", onPress: () => router.replace("/login") },
]);
}
} catch (err: any) {
const errMsg = err?.response?.data?.detail || "Invalid code or reset failed.";
setOtpError(errMsg);
if (Platform.OS === "web") {
window.alert(errMsg);
} else {
Alert.alert("Error", errMsg);
}
} finally {
setIsLoading(false);
}
};
return (
<SafeAreaView style={styles.safeArea}>
<KeyboardAvoidingView
style={styles.keyboardContainer}
behavior={Platform.OS === "ios" ? "padding" : undefined}
>
<ScrollView
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.contentContainer}
>
<View style={styles.container}>
{/* Header */}
<View style={styles.header}>
<Text style={styles.title}>Reset Password</Text>
<Text style={styles.subtitle}>
{step === "request"
? "Enter your registered email to receive a 6-digit verification code."
: `Enter the 6-digit code sent to ${email} and your new password.`}
</Text>
</View>
{step === "request" ? (
<View style={styles.form}>
<View style={styles.field}>
<FieldLabel label="Registered Email" required />
<BaseTextInput
value={email}
onChangeText={setEmail}
placeholder="doctor@example.com"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
leftIcon="mail-outline"
error={emailError}
/>
</View>
<View style={styles.buttonSpacing}>
<PrimaryButton
title="Send Verification Code"
loading={isLoading}
onPress={handleRequestOtp}
/>
</View>
<Pressable
style={styles.backButton}
onPress={() => router.back()}
>
<Text style={styles.backButtonText}>&larr; Back to Log In</Text>
</Pressable>
</View>
) : (
<View style={styles.form}>
<View style={styles.field}>
<FieldLabel label="6-Digit Verification Code" required />
<BaseTextInput
value={otpCode}
onChangeText={(val) => setOtpCode(val.replace(/\D/g, "").slice(0, 6))}
placeholder="123456"
keyboardType="number-pad"
autoCapitalize="none"
leftIcon="key-outline"
error={otpError}
/>
</View>
<View style={styles.field}>
<FieldLabel label="New Password" required />
<PasswordInput
value={newPassword}
onChangeText={setNewPassword}
placeholder="Min 8 chars (1 uppercase, 1 digit, 1 special)"
error={passwordError}
/>
</View>
<View style={styles.field}>
<FieldLabel label="Confirm New Password" required />
<PasswordInput
value={confirmPassword}
onChangeText={setConfirmPassword}
placeholder="Confirm new password"
error={confirmError}
/>
</View>
<View style={styles.buttonSpacing}>
<PrimaryButton
title="Reset Password"
loading={isLoading}
onPress={handleResetPassword}
/>
</View>
<View style={styles.footerRow}>
<Pressable onPress={() => setStep("request")}>
<Text style={styles.resendText}>Resend code</Text>
</Pressable>
<Pressable onPress={() => router.replace("/login")}>
<Text style={styles.backButtonText}>Back to Log In</Text>
</Pressable>
</View>
</View>
)}
</View>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: Colors.background,
},
keyboardContainer: {
flex: 1,
},
contentContainer: {
flexGrow: 1,
paddingBottom: verticalScale(32),
},
container: {
flex: 1,
paddingHorizontal: moderateScale(24),
paddingTop: verticalScale(30),
},
header: {
marginBottom: verticalScale(24),
},
title: {
fontSize: moderateScale(26),
fontWeight: "800",
color: Colors.text,
marginBottom: verticalScale(8),
},
subtitle: {
fontSize: moderateScale(14),
color: Colors.textSecondary,
lineHeight: moderateScale(20),
},
form: {
marginTop: verticalScale(8),
},
field: {
marginBottom: verticalScale(16),
},
buttonSpacing: {
marginTop: verticalScale(12),
},
backButton: {
alignSelf: "center",
marginTop: verticalScale(20),
padding: moderateScale(8),
},
backButtonText: {
fontSize: moderateScale(14),
fontWeight: "700",
color: AuthColors.primary,
},
footerRow: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginTop: verticalScale(20),
},
resendText: {
fontSize: moderateScale(14),
fontWeight: "600",
color: Colors.textSecondary,
},
});