import { useAlert } from '@/components/AlertComponent'; import api from '@/utils/api'; import { AuthContext } from '@/utils/authContext'; import { Eye, EyeOff, Lock, LogIn, Mail } from 'lucide-react-native'; import React, { useContext, useState } from 'react'; import { Image, Platform, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { KeyboardAvoidingView } from 'react-native-keyboard-controller'; export default function LoginScreen() { const alert = useAlert(); const authContext = useContext(AuthContext); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); // Login Handler function const handleLogin = async () => { if (!username || !password) { alert.showAlert('error', 'Attenzione', 'Inserisci username e password'); return; } setIsLoading(true); try { username.trim(); password.trim(); // Execute login request const response = await api.post("/user/login", { username: username, password: password }); const { token, user } = response.data; console.log("Login riuscito. Token:", token); console.log("Dati utente:", user); // Pass token and user data to the context which will handle saving and redirect authContext.logIn(token, user); } catch (error: any) { console.error("Login Error:", error); let message = "Si è verificato un errore durante l'accesso."; if (error.response) { // Server error (e.g., 401 Invalid credentials) if (error.response.status === 401) { message = "Credenziali non valide." } else { message = `Errore Server: ${error.response.data.message || error.response.status}`; } } else if (error.request) { // Server not reachable message = "Impossibile contattare il server. Controlla la connessione."; } alert.showAlert('error', "Login Fallito", message); } finally { setIsLoading(false); } }; return ( {/* Header with Logo/Title */} {/* Form Container */} {/* Input Username / Email */} Username o Email {/* Input Password */} Password setShowPassword(!showPassword)}> {showPassword ? ( ) : ( )} {/* TODO: Implement password recovery functionality */} Password dimenticata? {/* Login Button */} {isLoading ? 'Accesso in corso...' : 'Accedi'} {!isLoading && } ); }