import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:afterwork/data/models/event_model.dart'; import 'package:afterwork/data/models/user_model.dart'; import 'package:afterwork/core/constants/urls.dart'; import '../location/location_picker_screen.dart'; /// Classe représentant la boîte de dialogue pour ajouter un nouvel événement. /// Cette boîte de dialogue permet à l'utilisateur de remplir les détails d'un nouvel événement. class AddEventDialog extends StatefulWidget { final String userId; final String userName; final String userLastName; const AddEventDialog({ super.key, required this.userId, required this.userName, required this.userLastName, }); @override _AddEventDialogState createState() => _AddEventDialogState(); } class _AddEventDialogState extends State { final _formKey = GlobalKey(); // Clé globale pour valider le formulaire String _title = ''; String _description = ''; DateTime? _selectedDate; String? _imagePath; String _location = 'Abidjan'; // Par défaut à Cocody, Abidjan String _category = ''; String _link = ''; LatLng? _selectedLatLng = const LatLng(5.348722, -3.985038); // Par défaut à Cocody, Abidjan @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), ), backgroundColor: const Color(0xFF2C2C3E), child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, // Formulaire clé pour valider l'entrée des utilisateurs child: Column( mainAxisSize: MainAxisSize.min, children: [ _buildTitleField(), const SizedBox(height: 10), _buildDescriptionField(), const SizedBox(height: 10), _buildDatePicker(), const SizedBox(height: 10), _buildLocationField(context), const SizedBox(height: 10), _buildCategoryField(), const SizedBox(height: 10), _buildImagePicker(), const SizedBox(height: 10), _buildLinkField(), const SizedBox(height: 20), _buildSubmitButton(), ], ), ), ), ), ); } /// Construction du champ de saisie du titre de l'événement. Widget _buildTitleField() { return TextFormField( decoration: InputDecoration( labelText: 'Titre', labelStyle: const TextStyle(color: Colors.white70), filled: true, fillColor: Colors.white.withOpacity(0.1), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide.none, ), prefixIcon: const Icon(Icons.title, color: Colors.white70), ), style: const TextStyle(color: Colors.white), validator: (value) { if (value == null || value.isEmpty) { print('Erreur: Titre est vide'); return 'Veuillez entrer un titre'; } return null; }, onSaved: (value) { _title = value ?? ''; print('Titre sauvegardé: $_title'); }, ); } /// Construction du champ de saisie de la description de l'événement. Widget _buildDescriptionField() { return TextFormField( decoration: InputDecoration( labelText: 'Description', labelStyle: const TextStyle(color: Colors.white70), filled: true, fillColor: Colors.white.withOpacity(0.1), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide.none, ), prefixIcon: const Icon(Icons.description, color: Colors.white70), ), style: const TextStyle(color: Colors.white), maxLines: 3, validator: (value) { if (value == null || value.isEmpty) { print('Erreur: Description est vide'); return 'Veuillez entrer une description'; } return null; }, onSaved: (value) { _description = value ?? ''; print('Description sauvegardée: $_description'); }, ); } /// Widget pour le sélecteur de date pour l'événement. Widget _buildDatePicker() { return GestureDetector( onTap: () async { final DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime.now(), lastDate: DateTime(2101), ); if (picked != null && picked != _selectedDate) { setState(() { _selectedDate = picked; print('Date sélectionnée: $_selectedDate'); }); } else { print('Date non sélectionnée ou égale à la précédente'); } }, child: Container( padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0), decoration: BoxDecoration( color: Colors.white.withOpacity(0.1), borderRadius: BorderRadius.circular(10.0), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _selectedDate == null ? 'Sélectionnez une date' : '${_selectedDate!.day}/${_selectedDate!.month}/${_selectedDate!.year}', style: const TextStyle(color: Colors.white70), ), const Icon(Icons.calendar_today, color: Colors.white70), ], ), ), ); } /// Construction du champ de localisation pour l'événement. Widget _buildLocationField(BuildContext context) { return GestureDetector( onTap: () async { final LatLng? pickedLocation = await Navigator.push( context, MaterialPageRoute( builder: (context) => const LocationPickerScreen(), ), ); if (pickedLocation != null) { setState(() { _selectedLatLng = pickedLocation; _location = '${pickedLocation.latitude}, ${pickedLocation.longitude}'; print('Localisation sélectionnée: $_location'); }); } else { print('Localisation non sélectionnée'); } }, child: Container( padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0), decoration: BoxDecoration( color: Colors.white.withOpacity(0.1), borderRadius: BorderRadius.circular(10.0), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _selectedLatLng == null ? 'Sélectionnez une localisation' : 'Localisation: $_location', style: const TextStyle(color: Colors.white70), ), const Icon(Icons.location_on, color: Colors.white70), ], ), ), ); } /// Construction du champ de saisie de la catégorie de l'événement. Widget _buildCategoryField() { return TextFormField( decoration: InputDecoration( labelText: 'Catégorie', labelStyle: const TextStyle(color: Colors.white70), filled: true, fillColor: Colors.white.withOpacity(0.1), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide.none, ), prefixIcon: const Icon(Icons.category, color: Colors.white70), ), style: const TextStyle(color: Colors.white), onSaved: (value) { _category = value ?? ''; print('Catégorie sauvegardée: $_category'); }, ); } /// Construction du champ de sélection d'image pour l'événement. Widget _buildImagePicker() { return GestureDetector( onTap: () { // Logique pour sélectionner une image print('Image Picker activé'); }, child: Container( padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0), decoration: BoxDecoration( color: Colors.white.withOpacity(0.1), borderRadius: BorderRadius.circular(10.0), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _imagePath == null ? 'Sélectionnez une image' : 'Image sélectionnée: $_imagePath', style: const TextStyle(color: Colors.white70), ), const Icon(Icons.image, color: Colors.white70), ], ), ), ); } /// Construction du champ de saisie du lien associé à l'événement. Widget _buildLinkField() { return TextFormField( decoration: InputDecoration( labelText: 'Lien (optionnel)', labelStyle: const TextStyle(color: Colors.white70), filled: true, fillColor: Colors.white.withOpacity(0.1), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide.none, ), prefixIcon: const Icon(Icons.link, color: Colors.white70), ), style: const TextStyle(color: Colors.white), onSaved: (value) { _link = value ?? ''; print('Lien sauvegardé: $_link'); }, ); } /// Construction du bouton de soumission pour ajouter l'événement. Widget _buildSubmitButton() { return ElevatedButton( onPressed: () async { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); print('Formulaire validé'); // Créer l'événement en utilisant l'ID réel de l'utilisateur pour le créateur et les participants EventModel newEvent = EventModel( id: '', title: _title, description: _description, date: _selectedDate?.toIso8601String() ?? '', location: _location, category: _category, link: _link, imageUrl: _imagePath ?? '', creator: UserModel( userId: widget.userId, nom: widget.userName, prenoms: widget.userLastName, email: '', motDePasse: '', ), participants: [ UserModel( userId: widget.userId, nom: widget.userName, prenoms: widget.userLastName, email: '', motDePasse: '', ) ], ); // Convertir l'événement en JSON Map eventData = newEvent.toJson(); print('Données JSON de l\'événement: $eventData'); // Envoyer la requête POST à l'API final response = await http.post( Uri.parse('${Urls.baseUrl}/events'), headers: {'Content-Type': 'application/json'}, body: jsonEncode(eventData), ); print('Statut de la réponse: ${response.statusCode}'); print('Réponse brute: ${response.body}'); if (response.statusCode == 201) { // Création réussie print('Événement créé avec succès'); Navigator.of(context).pop(); // Ne passez pas de valeur ici } else { // Gérer l'erreur print('Erreur lors de la création de l\'événement: ${response.reasonPhrase}'); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Erreur: ${response.reasonPhrase}')), ); } } else { print('Le formulaire n\'est pas valide'); } }, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF1DBF73), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), padding: const EdgeInsets.symmetric(vertical: 12.0), minimumSize: const Size(double.infinity, 40), ), child: const Text('Ajouter l\'événement', style: TextStyle(color: Colors.white)), ); } }