import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:travel_mate/blocs/trip/trip_bloc.dart';
import 'package:travel_mate/blocs/trip/trip_event.dart';
import 'package:travel_mate/components/home/create_trip_content.dart';
import 'package:travel_mate/models/trip.dart';
import 'package:url_launcher/url_launcher.dart'; // Ajouter cet import
import 'package:travel_mate/components/map/map_content.dart'; // Ajouter cet import si la page carte existe

class ShowTripDetailsContent extends StatefulWidget {
  final Trip trip;
  const ShowTripDetailsContent({super.key, required this.trip});

  @override
  State<ShowTripDetailsContent> createState() => _ShowTripDetailsContentState();
}

class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
  // Méthode pour ouvrir la carte interne
  void _openInternalMap() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MapContent(
          initialSearchQuery: widget.trip.location,
        ),
      ),
    );
  }

  // Méthode pour ouvrir Google Maps
  Future<void> _openGoogleMaps() async {
    final location = Uri.encodeComponent(widget.trip.location);
    final url = 'https://www.google.com/maps/search/?api=1&query=$location';
    
    try {
      final uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        // Fallback: essayer l'URL scheme pour l'app mobile
        final appUrl = 'comgooglemaps://?q=$location';
        final appUri = Uri.parse(appUrl);
        if (await canLaunchUrl(appUri)) {
          await launchUrl(appUri);
        } else {
          // Si rien ne marche, afficher un message d'erreur
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Impossible d\'ouvrir Google Maps. Vérifiez que l\'application est installée.'),
                backgroundColor: Colors.red,
              ),
            );
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Erreur lors de l\'ouverture de Google Maps: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    final textColor = isDarkMode ? Colors.white : Colors.black;
    final secondaryTextColor = isDarkMode ? Colors.white70 : Colors.grey[600];
    
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.trip.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.trip.title,
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: textColor,
              ),
            ),
            SizedBox(height: 8),
            Text(
              widget.trip.description,
              style: TextStyle(color: textColor),
            ),
            SizedBox(height: 16),
            Row(
              children: [
                Icon(Icons.location_on, size: 16, color: secondaryTextColor),
                SizedBox(width: 8),
                Text(
                  widget.trip.location,
                  style: TextStyle(fontSize: 14, color: secondaryTextColor),
                ),
              ],
            ),
            SizedBox(height: 8),
            Row(
              children: [
                Icon(Icons.calendar_today, size: 16, color: secondaryTextColor),
                SizedBox(width: 8),
                Text(
                  '${widget.trip.startDate.day}/${widget.trip.startDate.month}/${widget.trip.startDate.year} - ${widget.trip.endDate.day}/${widget.trip.endDate.month}/${widget.trip.endDate.year}',
                  style: TextStyle(fontSize: 14, color: secondaryTextColor),
                ),
              ],
            ),
            SizedBox(height: 8),
            Row(
              children: [
                Icon(Icons.group, size: 16, color: secondaryTextColor),
                SizedBox(width: 8),
                Text(
                  '${widget.trip.participants.length} participant${widget.trip.participants.length > 1 ? 's' : ''}',
                  style: TextStyle(
                    fontSize: 14,
                    color: secondaryTextColor,
                  ),
                ),
              ],
            ),
            SizedBox(height: 16),
            Text(
              'Budget: ${widget.trip.budget ?? 'N/A'}€',
              style: TextStyle(color: textColor),
            ),
            SizedBox(height: 24),

            // Section des boutons de carte
            Text(
              'Explorer la destination',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: textColor,
              ),
            ),
            SizedBox(height: 16),

            // Boutons en ligne
            Row(
              children: [
                // Bouton carte interne
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _openInternalMap,
                    icon: Icon(Icons.map, color: Colors.white),
                    label: Text(
                      'Voir sur la carte',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).colorScheme.primary,
                      padding: EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 12),
                
                // Bouton Google Maps
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _openGoogleMaps,
                    icon: Icon(Icons.directions, color: Colors.white),
                    label: Text(
                      'Google Maps',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green[700],
                      padding: EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                  ),
                ),
              ],
            ),

            SizedBox(height: 24),

            // Boutons existants
            SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: () async {
                  final result = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => CreateTripContent(
                        tripToEdit: widget.trip,
                      ),
                    ),
                  );
                  
                  
                  if (result == true && mounted) {
                    Navigator.pop(context, true); // Retour avec flag
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color.fromARGB(255, 0, 123, 255),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text(
                  'Modifier les informations du voyage',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
            SizedBox(height: 16),
            SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: Text('Confirmer la suppression'),
                      content: Text(
                          'Êtes-vous sûr de vouloir supprimer ce voyage ? Cette action est irréversible.'),
                      actions: [
                        TextButton(
                          onPressed: () => Navigator.pop(context),
                          child: Text('Annuler'),
                        ),
                        TextButton(
                          onPressed: () {
                            context.read<TripBloc>().add(TripDeleteRequested(tripId: widget.trip.id!));
                            Navigator.pop(context); // Fermer le dialogue
                            Navigator.pop(context, true); // Retourner à l'écran précédent
                          },
                          child: Text(
                            'Supprimer',
                            style: TextStyle(color: Colors.red),
                          ),
                        ),
                      ],
                    ),
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text(
                  'Supprimer le voyage',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}