acupedia-mobile-ui/src/features/auth/components/LoginForm.tsx

181 lines
4.7 KiB
TypeScript

import React, { useState } from "react";
import {
Alert,
Pressable,
StyleSheet,
Text,
View,
} from "react-native";
import { useRouter } from "expo-router";
import {
moderateScale,
verticalScale,
} from "react-native-size-matters";
import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import { AuthColors } from "../constants/colors";
import { validateEmail } from "@/constants/countries";
import { useAuthStore } from "@/store/auth.store";
import { LoginMethod } from "./LoginTabs";
import { login } from "@/features/auth/api/auth.api";
interface LoginFormProps {
activeTab: LoginMethod;
}
export default function LoginForm({
activeTab,
}: LoginFormProps) {
const router = useRouter();
const establishSession = useAuthStore((state) => state.establishSession);
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [password, setPassword] = useState("");
const [emailError, setEmailError] = useState("");
const [phoneError, setPhoneError] = useState("");
const [passwordError, setPasswordError] = useState("");
const handlePhoneChange = (text: string) => {
const digits = text.replace(/\D/g, "");
setPhone(digits.slice(0, 15));
if (phoneError) setPhoneError("");
};
const handleLogin = async () => {
let hasError = false;
setEmailError("");
setPhoneError("");
setPasswordError("");
if (activeTab === "email") {
const emailErr = validateEmail(email);
if (emailErr) {
setEmailError(emailErr);
hasError = true;
}
} else {
if (!phone.trim()) {
setPhoneError("Phone number is required");
hasError = true;
} else if (phone.length < 7 || phone.length > 15) {
setPhoneError("Phone number must be between 7 and 15 digits");
hasError = true;
}
}
if (!password) {
setPasswordError("Password is required");
hasError = true;
} else if (/\s/.test(password)) {
setPasswordError("Password must not contain spaces");
hasError = true;
}
if (hasError) return;
try {
// Prepare login payload
const payload: any = { password };
if (activeTab === "email") {
payload.email = email.trim().toLowerCase();
} else {
payload.phone_number = phone.trim();
}
const response = await login(payload);
await establishSession(response);
// Navigate to Home only after the token is installed and initial
// identity/access refresh has been attempted.
router.replace("/");
} catch (err: any) {
let errMsg = "Invalid credentials. Please try again.";
const detail = err.response?.data?.detail;
if (typeof detail === "string") {
errMsg = detail;
} else if (Array.isArray(detail) && detail.length > 0) {
errMsg = detail[0].msg || JSON.stringify(detail[0]);
} else if (err.message) {
errMsg = err.message;
}
alert("Login Failed: " + errMsg);
}
};
return (
<View style={styles.container}>
{activeTab === "email" ? (
<BaseTextInput
value={email}
onChangeText={setEmail}
placeholder="Email Address"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
textContentType="emailAddress"
leftIcon="mail-outline"
error={emailError}
/>
) : (
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder="Phone Number"
keyboardType="number-pad"
autoCapitalize="none"
autoCorrect={false}
textContentType="telephoneNumber"
maxLength={15}
leftIcon="call-outline"
error={phoneError}
/>
)}
<PasswordInput
value={password}
onChangeText={setPassword}
error={passwordError}
/>
<Pressable
accessibilityRole="button"
style={styles.forgotButton}
onPress={() => {
router.push("/login/forgot-password");
}}
>
<Text style={styles.forgotText}>
Forgot Password?
</Text>
</Pressable>
<PrimaryButton
title="Log In"
onPress={handleLogin}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginTop: verticalScale(10),
},
forgotButton: {
alignSelf: "flex-end",
marginTop: verticalScale(4),
marginBottom: verticalScale(20),
},
forgotText: {
fontSize: moderateScale(14),
fontWeight: "600",
color: AuthColors.primary,
},
});