import React, { useState, useEffect, useRef } from 'react'; import { Text, View, TouchableOpacity, KeyboardAvoidingView, Platform, ScrollView, ImageBackground, ActivityIndicator, StatusBar, Keyboard, } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import Icon from 'react-native-vector-icons/Ionicons'; import { getStyles } from './login.styles'; import { useTheme } from '@theme'; import { useAppDispatch, useAppSelector, RootState, login, sendFcmToken } from '@store'; import { LoginRequest } from '@interfaces'; import { NotificationService } from '@services'; import { backGroundImage } from '@utils'; import { FormInput } from '@components'; import config from 'react-native-config'; import AsyncStorage from '@react-native-async-storage/async-storage'; export const LoginScreen = () => { const dispatch = useAppDispatch(); const navigation = useNavigation(); const { theme: colors, isDark } = useTheme(); const styles = getStyles(colors, isDark); const [tenancy, setTenancy] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [focusedField, setFocusedField] = useState(null); const scrollViewRef = useRef(null); const [localError, setLocalError] = useState(''); const [deviceToken, setDeviceToken] = useState(null); const { loginLoading, loginError, loginSuccess, token, user_data } = useAppSelector((state: RootState) => state.auth); const handleLogin = async () => { setLocalError(''); if (!tenancy.trim()) { setLocalError('Tenancy name is required'); return; } if (!email.trim()) { setLocalError('Email address is required'); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email.trim())) { setLocalError('Please enter a valid email address'); return; } if (!password.trim()) { setLocalError('Password is required'); return; } const fcmToken = await NotificationService.getFCMToken(); setDeviceToken(fcmToken); console.log('deviceToken-', fcmToken) const payload: LoginRequest = { email, password, device_token: fcmToken ?? '', }; const cleanTenancy = tenancy.trim().replace(/^(https?:\/\/)?/, ''); const fullTenancy = `https://${cleanTenancy}`; console.log('payload-', payload) console.log('tenancy-', config.BASE_URL) if (fullTenancy === config.BASE_URL) { try { await AsyncStorage.setItem('base_url', fullTenancy); await AsyncStorage.setItem('email', email); await AsyncStorage.setItem('password', password); } catch (e) { console.error('Failed to save login credentials to AsyncStorage', e); } await dispatch(login(payload)); } else { setLocalError('Invalid tenancy name'); } }; useEffect(() => { const loadCredentials = async () => { try { const savedBaseUrl = await AsyncStorage.getItem('base_url'); const savedEmail = await AsyncStorage.getItem('email'); const savedPassword = await AsyncStorage.getItem('password'); if (savedBaseUrl) { const cleanBaseUrl = savedBaseUrl.replace(/^(https?:\/\/)?/, ''); setTenancy(cleanBaseUrl); } if (savedEmail) setEmail(savedEmail); if (savedPassword) setPassword(savedPassword); } catch (e) { console.error('Failed to load login credentials from AsyncStorage', e); } }; loadCredentials(); }, []); useEffect(() => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if ( tenancy.trim() && email.trim() && emailRegex.test(email.trim()) && password.trim() ) { setLocalError(''); } }, [tenancy, email, password]); useEffect(() => { if (loginSuccess && token && user_data) { // Send FCM token to server immediately after login if (deviceToken && user_data.staffid) { dispatch(sendFcmToken({ id: user_data.staffid, fcm_token: deviceToken })); } navigation.reset({ index: 0, routes: [{ name: 'DrawerStack' }], }); // Show permission popup after the user has landed in the app setTimeout(() => NotificationService.requestPermission(), 1000); } }, [loginSuccess, token, user_data, navigation]); return ( {/* Top Area Spacer displaying background illustration */} {/* Bottom Sheet Form Card */} Sign In Enter your credentials to continue {localError || loginError ? ( {localError || loginError} ) : null} {/* Tenancy Field */} { const cleaned = text.replace(/^(https?:\/\/)?/, ''); setTenancy(cleaned); }} prefix="https://" placeholder="company-name" autoCapitalize="none" autoCorrect={false} containerStyle={styles.fieldContainer} inputContainerStyle={[ styles.inputWrapper, focusedField === 'tenancy' && styles.inputWrapperFocused, ]} onFocus={() => { setFocusedField('tenancy'); setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100); }} onBlur={() => setFocusedField(null)} leftIcon={ } /> {/* Email Field */} { setFocusedField('email'); setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100); }} onBlur={() => setFocusedField(null)} leftIcon={ } /> {/* Password Field */} { setFocusedField('password'); setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100); }} onBlur={() => setFocusedField(null)} leftIcon={ } rightIcon={ setShowPassword(!showPassword)} style={styles.eyeIconButton} activeOpacity={0.7} > } /> {/* Sign In Button */} {loginLoading ? ( ) : ( Sign In )} ); };