import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:em2rp/models/event_model.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:url_launcher/url_launcher.dart';

class EventDetailsDescription extends StatelessWidget {
  final EventModel event;

  const EventDetailsDescription({
    super.key,
    required this.event,
  });

  @override
  Widget build(BuildContext context) {
    final bool isMobile = MediaQuery.of(context).size.width < 600;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Description',
          style: Theme.of(context).textTheme.titleLarge?.copyWith(
                color: AppColors.noir,
                fontWeight: FontWeight.bold,
              ),
        ),
        const SizedBox(height: 8),
        SelectableText(
          event.description.isEmpty ? 'Aucune description' : event.description,
          style: Theme.of(context).textTheme.bodyLarge,
        ),
        const SizedBox(height: 16),

        // Informations de contact et jauge
        if (event.jauge != null || event.contactEmail != null || event.contactPhone != null) ...[
          isMobile ? _buildContactInfoMobile(context) : _buildContactInfoDesktop(context),
          const SizedBox(height: 16),
        ],

        Text(
          'Adresse',
          style: Theme.of(context).textTheme.titleLarge?.copyWith(
                color: AppColors.noir,
                fontWeight: FontWeight.bold,
              ),
        ),
        const SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SelectableText(
                    event.address,
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),
                  if (event.latitude != 0.0 || event.longitude != 0.0) ...[
                    const SizedBox(height: 4),
                    SelectableText(
                      '${event.latitude}° N, ${event.longitude}° E',
                      style: Theme.of(context).textTheme.bodySmall,
                    ),
                  ],
                ],
              ),
            ),
            IconButton(
              icon: const Icon(Icons.map, color: AppColors.rouge),
              tooltip: 'Ouvrir dans Maps',
              onPressed: () async {
                final query = event.address;
                if (query.isEmpty) return;
                
                final url = Uri.parse('https://www.google.com/maps/search/?api=1&query=${Uri.encodeComponent(query)}');
                if (await canLaunchUrl(url)) {
                  await launchUrl(url, mode: LaunchMode.externalApplication);
                } else {
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Impossible d\'ouvrir l\'application de carte')),
                    );
                  }
                }
              },
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildContactInfoMobile(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (event.jauge != null) ...[
          _buildInfoRow(context, Icons.people, 'Jauge', '${event.jauge} personnes'),
          const SizedBox(height: 8),
        ],
        if (event.contactEmail != null && event.contactEmail!.isNotEmpty) ...[
          _buildInfoRow(context, Icons.email, 'Email', event.contactEmail!, onTap: () async {
            final url = Uri.parse('mailto:${event.contactEmail!}');
            if (await canLaunchUrl(url)) {
              await launchUrl(url);
            }
          }),
          const SizedBox(height: 8),
        ],
        if (event.contactPhone != null && event.contactPhone!.isNotEmpty) ...[
          _buildInfoRow(context, Icons.phone, 'Téléphone', event.contactPhone!, onTap: () async {
            final url = Uri.parse('tel:${event.contactPhone!}');
            if (await canLaunchUrl(url)) {
              await launchUrl(url);
            }
          }),
        ],
      ],
    );
  }

  Widget _buildContactInfoDesktop(BuildContext context) {
    return Wrap(
      spacing: 24,
      runSpacing: 12,
      children: [
        if (event.jauge != null)
          _buildInfoChip(context, Icons.people, 'Jauge', '${event.jauge} personnes'),
        if (event.contactEmail != null && event.contactEmail!.isNotEmpty)
          _buildInfoChip(context, Icons.email, 'Email', event.contactEmail!, onTap: () async {
            final url = Uri.parse('mailto:${event.contactEmail!}');
            if (await canLaunchUrl(url)) {
              await launchUrl(url);
            }
          }),
        if (event.contactPhone != null && event.contactPhone!.isNotEmpty)
          _buildInfoChip(context, Icons.phone, 'Téléphone', event.contactPhone!, onTap: () async {
            final url = Uri.parse('tel:${event.contactPhone!}');
            if (await canLaunchUrl(url)) {
              await launchUrl(url);
            }
          }),
      ],
    );
  }

  Widget _buildInfoRow(BuildContext context, IconData icon, String label, String value, {VoidCallback? onTap}) {
    return Row(
      children: [
        Icon(icon, size: 20, color: Theme.of(context).primaryColor),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: Theme.of(context).textTheme.labelSmall?.copyWith(
                      color: Colors.grey[600],
                    ),
              ),
              onTap == null
                  ? SelectableText(
                      value,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            fontWeight: FontWeight.w500,
                          ),
                    )
                  : SelectableText.rich(
                      TextSpan(
                        text: value,
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w500,
                              color: AppColors.rouge,
                              decoration: TextDecoration.underline,
                            ),
                        recognizer: TapGestureRecognizer()..onTap = onTap,
                      ),
                    ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInfoChip(BuildContext context, IconData icon, String label, String value, {VoidCallback? onTap}) {
    final primaryColor = Theme.of(context).primaryColor;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: primaryColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: primaryColor.withOpacity(0.2)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 18, color: primaryColor),
          const SizedBox(width: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                label,
                style: Theme.of(context).textTheme.labelSmall?.copyWith(
                      color: Colors.grey[600],
                    ),
              ),
              onTap == null
                  ? SelectableText(
                      value,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                            fontWeight: FontWeight.w500,
                          ),
                    )
                  : SelectableText.rich(
                      TextSpan(
                        text: value,
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              fontWeight: FontWeight.w500,
                              color: AppColors.rouge,
                              decoration: TextDecoration.underline,
                            ),
                        recognizer: TapGestureRecognizer()..onTap = onTap,
                      ),
                    ),
            ],
          ),
        ],
      ),
    );
  }
}

