import 'dart:async'; import 'package:afterwork/data/datasources/user_remote_data_source.dart'; import 'package:afterwork/data/models/user_model.dart'; import 'package:afterwork/data/services/preferences_helper.dart'; import 'package:afterwork/data/services/secure_storage.dart'; import 'package:afterwork/presentation/screens/home/home_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:http/http.dart' as http; import 'package:loading_icon_button/loading_icon_button.dart'; import 'package:provider/provider.dart'; import '../../../core/theme/theme_provider.dart'; import '../../../data/datasources/event_remote_data_source.dart'; import '../signup/SignUpScreen.dart'; /// Écran de connexion pour l'application AfterWork. /// Ce fichier contient des fonctionnalités comme la gestion de la connexion, /// l'authentification avec mot de passe en clair, la gestion des erreurs et un thème jour/nuit. class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State with SingleTickerProviderStateMixin { final _formKey = GlobalKey(); // Clé pour valider le formulaire de connexion. // Champs utilisateur String _email = ''; // Email de l'utilisateur String _password = ''; // Mot de passe de l'utilisateur // États de gestion bool _isPasswordVisible = false; // Pour afficher/masquer le mot de passe bool _isSubmitting = false; // Indicateur pour l'état de soumission du formulaire bool _showErrorMessage = false; // Affichage des erreurs // Services pour les opérations final UserRemoteDataSource _userRemoteDataSource = UserRemoteDataSource(http.Client()); final SecureStorage _secureStorage = SecureStorage(); final PreferencesHelper _preferencesHelper = PreferencesHelper(); // Contrôleur pour le bouton de chargement final _btnController = LoadingButtonController(); // Contrôleur d'animation pour la transition des écrans late AnimationController _animationController; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 500), ); print("Contrôleur d'animation initialisé."); } @override void dispose() { _animationController.dispose(); print("Ressources d'animation libérées."); super.dispose(); } /// Fonction pour basculer la visibilité du mot de passe void _togglePasswordVisibility() { setState(() { _isPasswordVisible = !_isPasswordVisible; }); print("Visibilité du mot de passe basculée: $_isPasswordVisible"); } /// Fonction pour afficher un toast via FlutterToast void _showToast(String message) { Fluttertoast.showToast( msg: message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0, ); } /// Fonction soumettre le formulaire Future _submit() async { print("Tentative de soumission du formulaire de connexion."); if (_formKey.currentState!.validate()) { setState(() { _isSubmitting = true; _showErrorMessage = false; }); _formKey.currentState!.save(); try { _btnController.start(); final UserModel user = await _userRemoteDataSource.authenticateUser(_email, _password); if (user == null) { throw Exception("L'utilisateur n'a pas été trouvé ou l'authentification a échoué."); } print("Utilisateur authentifié : ${user.userId}"); await _secureStorage.saveUserId(user.userId); await _preferencesHelper.saveUserName(user.nom); await _preferencesHelper.saveUserLastName(user.prenoms); _showToast("Connexion réussie !"); // Navigation vers la page d'accueil Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => HomeScreen( eventRemoteDataSource: EventRemoteDataSource(http.Client()), userId: user.userId, userName: user.nom, userLastName: user.prenoms, userProfileImage: 'lib/assets/images/profile_picture.png', ), ), ); } catch (e) { print("Erreur lors de l'authentification : $e"); _btnController.error(); _showToast("Erreur lors de la connexion : ${e.toString()}"); setState(() { _showErrorMessage = true; }); } finally { _btnController.reset(); setState(() { _isSubmitting = false; }); } } else { print("Échec de validation du formulaire."); _btnController.reset(); _showToast("Veuillez vérifier les informations saisies."); } } @override Widget build(BuildContext context) { final theme = Theme.of(context); final size = MediaQuery.of(context).size; final themeProvider = Provider.of(context); bool isKeyboardVisible = MediaQuery.of(context).viewInsets.bottom != 0; return Scaffold( body: Stack( children: [ AnimatedContainer( duration: const Duration(seconds: 3), decoration: BoxDecoration( gradient: LinearGradient( colors: [ theme.colorScheme.primary, theme.colorScheme.secondary ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), ), if (_isSubmitting) const Center( child: SpinKitFadingCircle( color: Colors.white, size: 50.0, ), ), Positioned( top: 40, right: 20, child: IconButton( icon: Icon( themeProvider.isDarkMode ? Icons.dark_mode : Icons.light_mode, color: theme.iconTheme.color, ), onPressed: () { themeProvider.toggleTheme(); print("Thème basculé : ${themeProvider.isDarkMode ? 'Sombre' : 'Clair'}"); }, ), ), Center( child: SingleChildScrollView( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Image.asset( 'lib/assets/images/logo.png', height: size.height * 0.25, ), const SizedBox(height: 20), Text( 'Bienvenue sur AfterWork', style: theme.textTheme.titleLarge, ), const SizedBox(height: 40), _buildTextFormField( label: 'Email', icon: Icons.email, validator: (value) { if (value == null || value.isEmpty) { print("Erreur : champ email vide."); return 'Veuillez entrer votre email'; } if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) { print("Erreur : email invalide."); return 'Veuillez entrer un email valide'; } return null; }, onSaved: (value) { _email = value!; print("Email enregistré : $_email"); }, ), const SizedBox(height: 20), _buildTextFormField( label: 'Mot de passe', icon: Icons.lock, obscureText: !_isPasswordVisible, suffixIcon: IconButton( icon: Icon( _isPasswordVisible ? Icons.visibility : Icons.visibility_off, color: theme.iconTheme.color, ), onPressed: _togglePasswordVisibility, ), validator: (value) { if (value == null || value.isEmpty) { print("Erreur : champ mot de passe vide."); return 'Veuillez entrer votre mot de passe'; } if (value.length < 6) { print("Erreur : mot de passe trop court."); return 'Le mot de passe doit comporter au moins 6 caractères'; } return null; }, onSaved: (value) { _password = value!; print("Mot de passe enregistré."); }, ), const SizedBox(height: 30), SizedBox( width: size.width * 0.85, child: LoadingButton( controller: _btnController, onPressed: _isSubmitting ? null : _submit, iconData: Icons.login, iconColor: theme.colorScheme.onPrimary, child: Text( 'Connexion', style: theme.textTheme.bodyLarge!.copyWith( color: theme.colorScheme.onPrimary, ), ), ), ), const SizedBox(height: 20), TextButton( onPressed: () { print("Redirection vers la page d'inscription"); Navigator.push( context, MaterialPageRoute( builder: (context) => SignUpScreen(), ), ); }, child: Text( 'Pas encore de compte ? Inscrivez-vous', style: theme.textTheme.bodyMedium! .copyWith(color: Colors.white70), ), ), TextButton( onPressed: () { print("Mot de passe oublié"); }, child: Text( 'Mot de passe oublié ?', style: theme.textTheme.bodyMedium! .copyWith(color: Colors.white70), ), ), if (_showErrorMessage) const Padding( padding: EdgeInsets.only(top: 20), child: Text( 'Erreur lors de la connexion. Veuillez vérifier vos identifiants.', style: TextStyle(color: Colors.red, fontSize: 16), textAlign: TextAlign.center, ), ), ], ), ), ), ), AnimatedPositioned( duration: const Duration(milliseconds: 300), bottom: isKeyboardVisible ? 0 : 20, left: isKeyboardVisible ? 20 : 0, right: isKeyboardVisible ? 20 : 0, child: Row( mainAxisAlignment: isKeyboardVisible ? MainAxisAlignment.spaceBetween : MainAxisAlignment.center, children: [ Image.asset( 'lib/assets/images/logolionsdev.png', height: 30, ), if (isKeyboardVisible) Text( '© 2024 LionsDev', style: theme.textTheme.bodyMedium! .copyWith(color: Colors.white70), textAlign: TextAlign.center, ), ], ), ), ], ), ); } /// Widget réutilisable pour les champs de texte avec validation et design amélioré Widget _buildTextFormField({ required String label, required IconData icon, bool obscureText = false, Widget? suffixIcon, required FormFieldValidator validator, required FormFieldSetter onSaved, }) { final theme = Theme.of(context); return TextFormField( decoration: InputDecoration( labelText: label, filled: true, fillColor: theme.inputDecorationTheme.fillColor, labelStyle: theme.textTheme.bodyMedium, border: OutlineInputBorder( borderRadius: BorderRadius.circular(12.0), borderSide: BorderSide.none, ), prefixIcon: Icon(icon, color: theme.iconTheme.color), suffixIcon: suffixIcon, ), obscureText: obscureText, style: theme.textTheme.bodyLarge, validator: validator, onSaved: onSaved, ); } }