import React, { useState, useMemo } from "react"; import { KeyboardAvoidingView, Modal, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, View, } from "react-native"; import { useRouter } from "expo-router"; import { Ionicons } from "@expo/vector-icons"; import { moderateScale, scale, 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 { Colors } from "@/theme"; import { COUNTRY_CODES, CountryCode, DEFAULT_COUNTRY, validatePhoneNumber, validateEmail, } from "@/constants/countries"; import { useAuthStore } from "@/store/auth.store"; import { register } from "@/features/auth/api/auth.api"; export default function SignUpForm() { const router = useRouter(); const setRegisteredUser = useAuthStore((state) => state.setRegisteredUser); const [fullName, setFullName] = useState(""); const [email, setEmail] = useState(""); const [selectedCountry, setSelectedCountry] = useState(DEFAULT_COUNTRY); const [phone, setPhone] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [showCountryModal, setShowCountryModal] = useState(false); const [countrySearch, setCountrySearch] = useState(""); const [isLoading, setIsLoading] = useState(false); const [fullNameError, setFullNameError] = useState(""); const [emailError, setEmailError] = useState(""); const [phoneError, setPhoneError] = useState(""); const [passwordError, setPasswordError] = useState(""); const [confirmPasswordError, setConfirmPasswordError] = useState(""); const filteredCountries = useMemo(() => { const q = countrySearch.trim().toLowerCase(); if (!q) return COUNTRY_CODES; return COUNTRY_CODES.filter( (c) => c.country.toLowerCase().includes(q) || c.code.includes(q) || c.label.toLowerCase().includes(q) ); }, [countrySearch]); const handlePhoneChange = (text: string) => { const digits = text.replace(/\D/g, ""); setPhone(digits.slice(0, selectedCountry.maxLength)); if (phoneError) setPhoneError(""); }; const handleCountrySelect = (c: CountryCode) => { if (c.country !== selectedCountry.country) { setPhone(""); } setSelectedCountry(c); setShowCountryModal(false); setCountrySearch(""); if (phoneError) setPhoneError(""); }; const handleSignUp = async () => { let hasError = false; setFullNameError(""); setEmailError(""); setPhoneError(""); setPasswordError(""); setConfirmPasswordError(""); if (!fullName.trim()) { setFullNameError("Full name is required"); hasError = true; } const emailErr = validateEmail(email); if (emailErr) { setEmailError(emailErr); hasError = true; } if (phone.trim()) { const err = validatePhoneNumber( phone.trim(), selectedCountry.code, selectedCountry.country ); if (err) { setPhoneError(err); hasError = true; } } if (!password) { setPasswordError("Password is required"); hasError = true; } else if (password.length < 8) { setPasswordError("Password must be at least 8 characters"); hasError = true; } else if (/\s/.test(password)) { setPasswordError("Password must not contain spaces"); hasError = true; } else if (!/[A-Z]/.test(password)) { setPasswordError("Password must contain at least one uppercase letter (A-Z)"); hasError = true; } else if (!/[0-9]/.test(password)) { setPasswordError("Password must contain at least one number (0-9)"); hasError = true; } else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(password)) { setPasswordError("Password must contain at least one special character (!@#$)"); hasError = true; } if (!confirmPassword) { setConfirmPasswordError("Please confirm your password"); hasError = true; } else if (password !== confirmPassword) { setConfirmPasswordError("Passwords do not match"); hasError = true; } if (hasError) return; setIsLoading(true); try { const formattedPhone = phone.trim() ? `${selectedCountry.code}${phone.trim()}` : undefined; const response = await register({ email: email.trim().toLowerCase(), password, full_name: fullName.trim(), phone_number: formattedPhone, country: selectedCountry.country, }); const { user } = response; setRegisteredUser({ id: user.id, name: user.display_name ?? fullName.trim(), email: user.email, phone_number: user.phone_number ?? formattedPhone, country: user.country ?? selectedCountry.country, }); // Redirect directly to login screen without alert block router.replace("/login"); } catch (err: any) { let errMsg = "Something went wrong. 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]); } alert("Registration Failed: " + errMsg); } finally { setIsLoading(false); } }; return ( {/* Phone Number Field with Country Dial Code */} setShowCountryModal(true)} style={styles.dialCodeButton} > {selectedCountry.label} {phoneError ? ( {phoneError} ) : ( {selectedCountry.minLength === selectedCountry.maxLength ? `${selectedCountry.country}: Requires exactly ${selectedCountry.maxLength} digits` : `${selectedCountry.country}: ${selectedCountry.minLength} to ${selectedCountry.maxLength} digits`} )} {/* Country Selection Modal */} { setShowCountryModal(false); setCountrySearch(""); }} > { setShowCountryModal(false); setCountrySearch(""); }} /> Select Country { setShowCountryModal(false); setCountrySearch(""); }} > {/* Country Search Bar */} {countrySearch.length > 0 && ( setCountrySearch("")} > )} {filteredCountries.length === 0 ? ( No countries found ) : ( filteredCountries.map((c) => { const isSelected = selectedCountry.country === c.country; return ( [ styles.countryItem, isSelected && styles.countryItemSelected, pressed && styles.countryItemPressed, ]} onPress={() => handleCountrySelect(c)} > {c.label} {c.country} {isSelected && ( )} ); }) )} ); } const styles = StyleSheet.create({ container: { marginTop: verticalScale(10), }, buttonSpacing: { marginTop: verticalScale(10), }, phoneFieldWrapper: { marginBottom: verticalScale(18), }, phoneContainer: { flexDirection: "row", alignItems: "center", backgroundColor: AuthColors.inputBackground, borderWidth: 1, borderColor: AuthColors.border, borderRadius: moderateScale(16), paddingHorizontal: scale(12), height: verticalScale(56), }, dialCodeButton: { flexDirection: "row", alignItems: "center", paddingVertical: verticalScale(8), paddingHorizontal: scale(4), }, dialCodeText: { fontSize: moderateScale(14), fontWeight: "700", color: AuthColors.textPrimary, }, phoneDivider: { width: 1, height: verticalScale(28), backgroundColor: AuthColors.border, marginHorizontal: scale(10), }, phoneInput: { flex: 1, fontSize: moderateScale(15), color: AuthColors.textPrimary, paddingVertical: 0, }, errorBorder: { borderColor: AuthColors.danger, }, errorText: { color: AuthColors.danger, fontSize: moderateScale(12), marginTop: verticalScale(6), marginLeft: scale(6), }, phoneHelperText: { color: AuthColors.textSecondary, fontSize: moderateScale(11), marginTop: verticalScale(4), marginLeft: scale(6), }, modalOverlay: { flex: 1, backgroundColor: "rgba(0, 0, 0, 0.45)", justifyContent: "flex-end", }, modalSheet: { backgroundColor: "#FFFFFF", borderTopLeftRadius: moderateScale(20), borderTopRightRadius: moderateScale(20), maxHeight: "75%", paddingTop: verticalScale(16), paddingBottom: verticalScale(32), }, modalHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: scale(20), paddingBottom: verticalScale(12), borderBottomWidth: 1, borderBottomColor: "#F1F5F9", }, modalTitle: { fontSize: moderateScale(17), fontWeight: "700", color: Colors.textPrimary, }, countryList: { paddingHorizontal: scale(16), paddingTop: verticalScale(8), }, countryItem: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingVertical: verticalScale(12), paddingHorizontal: scale(12), borderRadius: moderateScale(10), }, countryItemSelected: { backgroundColor: "#DCFCE7", }, countryItemPressed: { backgroundColor: "#F1F5F9", }, countryRow: { flexDirection: "row", alignItems: "center", gap: scale(10), }, countryLabel: { fontSize: moderateScale(15), fontWeight: "600", color: Colors.textPrimary, minWidth: scale(65), }, countryName: { fontSize: moderateScale(14), color: Colors.textPrimary, fontWeight: "500", }, countryNameSelected: { fontWeight: "700", color: "#15803D", }, modalSearchContainer: { flexDirection: "row", alignItems: "center", backgroundColor: "#F8FAFC", borderWidth: 1, borderColor: "#E2E8F0", borderRadius: moderateScale(12), marginHorizontal: scale(16), marginTop: verticalScale(12), marginBottom: verticalScale(4), paddingHorizontal: scale(12), height: verticalScale(42), gap: scale(8), }, modalSearchInput: { flex: 1, fontSize: moderateScale(14), color: Colors.textPrimary, paddingVertical: 0, }, emptyContainer: { paddingVertical: verticalScale(32), alignItems: "center", justifyContent: "center", }, emptyText: { fontSize: moderateScale(14), color: AuthColors.textSecondary, fontWeight: "500", }, });