import React, { useState, useContext } from 'react'; import { Eye, EyeOff, Lock, LogIn, Mail } from 'lucide-react-native'; import { KeyboardAvoidingView, Platform, ScrollView, Text, TextInput, TouchableOpacity, View, Image, Alert } from 'react-native'; import { AuthContext } from '@/utils/authContext'; import api from '@/utils/api'; export default function LoginScreen() { const authContext = useContext(AuthContext); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); const handleLogin = async () => { // TODO: Implementa toast o messaggio di errore più user-friendly if (!username || !password) { Alert.alert("Attenzione", "Inserisci username e password"); return; } setIsLoading(true); try { console.log("Tentativo login con:", username); // Chiamata vera al backend const response = await api.post("/user/login", { username: username, password: password }); const { token, user } = response.data; console.log("Login successo, token ricevuto."); console.log("Dati utente:", user); // Passiamo token e dati utente al context che gestirà salvataggio e 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) { // Errore dal server (es. 401 Credenziali errate) 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 non raggiungibile message = "Impossibile contattare il server. Controlla la connessione."; } Alert.alert("Login Fallito", message); } finally { setIsLoading(false); } }; return ( {/* Header con Logo/Titolo */} {/* Form Container */} {/* Input Username / Email */} Username o Email {/* Input Password */} Password setShowPassword(!showPassword)}> {showPassword ? ( ) : ( )} Password dimenticata? {/* Tasto Login */} {isLoading ? 'Accesso in corso...' : 'Accedi'} {!isLoading && } ); }