// PhoneAuth.js
import React, { useRef, useState } from ‘react’;
import { Button, TextInput, View, Text,StyleSheet } from ‘react-native’;
import { signInWithPhoneNumber, PhoneAuthProvider, signInWithCredential } from ‘firebase/auth’;
import { FirebaseRecaptchaVerifierModal } from ‘expo-firebase-recaptcha’;
import firebaseConfig from ‘…/firebaseConfig’;
import PhoneInput from ‘react-native-phone-number-input’;
import { PhoneNumberUtil, PhoneNumberFormat } from ‘google-libphonenumber’;
import { MaterialIcons } from ‘@expo/vector-icons’;
import { useNavigation } from ‘@react-navigation/native’;
const PhoneAuthNative = ({ auth,getUserId }) => {
const [phoneNumber, setPhoneNumber] = useState(‘’);
const [code, setCode] = useState(‘’);
const [confirmationResult, setConfirmationResult] = useState(null);
const phoneNumberUtil = PhoneNumberUtil.getInstance();
const recaptchaVerifier = useRef(null);
const [isPhoneNumberValid, setIsPhoneNumberValid] = useState(false);
const [isSendCode, setIsSendCode] = useState(true)
const [errorMessage, setErrorMessage] = useState(‘’);
const navigation = useNavigation();
const [userId,setuserId]=useState(‘’)
const handleUserId=(id)=>{
getUserId(id)
setuserId(id)
}
const validatePhoneNumber = (parsedPhoneNumber) => {
try {
const isValid = phoneNumberUtil.isValidNumber(parsedPhoneNumber);
if (isValid) {
const formattedPhoneNumber = phoneNumberUtil.format(parsedPhoneNumber, PhoneNumberFormat.E164);
setPhoneNumber(formattedPhoneNumber)
signInWithPhoneNumberFunc(formattedPhoneNumber)
setErrorMessage(`Valid phone number: ${formattedPhoneNumber}`);
} else {
setErrorMessage('Phone number is invalid');
setIsPhoneNumberValid(false);
setPhoneNumber('');
}
return isValid;
} catch (error) {
setErrorMessage('Invalid phone number');
return false;
}
};
const handleCode = (newCode) => {
setCode(newCode);
confirmCode(newCode);
};
const handlePhoneChange = (formattedValue) => {
try {
const parsedPhoneNumber = phoneNumberUtil.parse(formattedValue, ‘LB’);
const isValid = validatePhoneNumber(parsedPhoneNumber);
if (isValid) {
console.log(phoneNumber)
setErrorMessage(‘Phone number is valid insert the confirmation code sent to your number’);
} else {
setErrorMessage(‘Phone number is invalid’);
setIsPhoneNumberValid(false);
setPhoneNumber(‘’);
}
} catch (error) {
setErrorMessage(error.message);
return false;
}
};
const signInWithPhoneNumberFunc = async (phone) => {
try {
const phoneProvider = new PhoneAuthProvider(auth);
const verificationId = await phoneProvider.verifyPhoneNumber(phone, recaptchaVerifier.current);
setConfirmationResult({ verificationId });
setIsPhoneNumberValid(true);
setIsSendCode(false);
} catch (error) {
setIsSendCode(true);
setConfirmationResult(null);
console.log(‘Error:’, error.message);
}
};
const confirmCode = async (x) => {
try {
if (confirmationResult) {
const credential = PhoneAuthProvider.credential(confirmationResult.verificationId, x);
const result = await signInWithCredential(auth, credential);
const user = result.user;
const uid = user.uid; // Access the user’s UID
handleUserId(uid);
console.log(‘user:’,uid)
setIsPhoneNumberValid(false);
setConfirmationResult(null);
console.log(isPhoneNumberValid);
setIsSendCode(true)
setErrorMessage(‘Your Phone Nmber is Confirmed’, result);
navigation.navigate(‘Home’, { userId: uid });
console.log(‘1234’)
} else {
setErrorMessage(‘No confirmation result available’);
}
} catch (error) {
setErrorMessage('Error confirming code',error.message);
}
};
return (
<View style={{width:'100%',paddingHorizontal:10}}>
{isSendCode &&
<View style={styles.inputContainer}>
<View style={styles.inputWrapper}>
<View style={{flexDirection:'row',marginBottom:-10}}>
Phone Number
<PhoneInput
defaultCode="LB"
placeholder="exp:3123456"
value={phoneNumber}
flagButtonStyle={styles.flag}
disableArrowIcon={false}
onChangeText={handlePhoneChange}
containerStyle={styles.phoneInputContainer}
textContainerStyle={styles.phoneInputTextContainer}
textInputStyle={styles.phoneInputText}
/>
<Text style={styles.errorMessage}>{errorMessage}</Text>
</View>
</View>
}
<View>
{confirmationResult && isPhoneNumberValid ? (
<View style={styles.inputContainer}>
<View style={styles.inputWrapper}>
<View style={{flexDirection:'row'}}>
Confirmation Code
<TextInput
value={code}
onChangeText={(text) => handleCode(text)}
placeholder="Insert Verification Code"
style={styles.phoneInputText}
/>
<Text style={styles.errorMessage}>{errorMessage}</Text>
</View>
</View>
) : null}</View>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={firebaseConfig}
attemptInvisibleVerification/>
</View>
);
};
const styles = StyleSheet.create({
inputContainer: {
flexDirection: ‘column’,
alignItems: ‘center’, // change from ‘left’ to ‘center’
marginVertical: 10,
width:‘100%’,
height:‘100%’,
},
iconWrapper: {
backgroundColor: ‘#fffff0’,
padding: 1,
paddingRight: 0, // reduce paddingRight
borderRadius: 25,
marginRight: 0, // remove marginRight
},
inputWrapper: {
flex: 1,
marginLeft: 0, // reduce marginLeft
marginHorizontal: 5,
width: ‘100%’
},
label: {
color: ‘#000000’,
fontSize: 16,
marginBottom: 5,
fontStyle: ‘italic’,
padding: 1,
},
phoneInputContainer: {
flexDirection: ‘row’,
backgroundColor: ‘white’,
width: ‘100%’,
alignSelf:‘flex-start’,
},
flag: {
width:‘20%’,
},
phoneInputTextContainer: {
paddingLeft: 0, // Remove paddingLeft
paddingStart: 0,
paddingStart: 0,
marginVertical: 0,
backgroundColor: ‘white’,
width:‘100%’,
color: ‘#7fffd4’,
},
phoneInputText: {
fontSize: 16,
paddingStart: 0,
paddingVertical: 5,
paddingLeft: 5, // Add paddingLeft
color: ‘#7fffd4’,
backgroundColor: ‘#f0ffff’,
width: ‘100%’,
alignSelf:‘center’,
color: ‘grey’,
borderBottomWidth:1,
},
senCodeButton: {
width: ‘75%’,
color: ‘black’,
borderRadius: 5,
backgroundColor: ‘lightblue’,
textAlign: “center”,
alignSelf: ‘center’,
},
errorMessage: {
color: ‘red’,
fontSize: 11,
marginTop: 5,
fontStyle: ‘italic’,
alignSelf:‘center’,
},
});
export default PhoneAuthNative;