import 'package:flutter/material.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:path/path.dart' as p;

class EventDetailsDocuments extends StatelessWidget {
  final List<Map<String, dynamic>> documents;

  const EventDetailsDocuments({
    super.key,
    required this.documents,
  });

  @override
  Widget build(BuildContext context) {
    if (documents.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 16),
        Text(
          'Documents',
          style: Theme.of(context).textTheme.titleLarge?.copyWith(
                color: AppColors.noir,
                fontWeight: FontWeight.bold,
              ),
        ),
        const SizedBox(height: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: documents.map((doc) {
            final fileName = doc['name'] ?? '';
            final url = doc['url'] ?? '';
            final ext = p.extension(fileName).toLowerCase();
            IconData icon;

            if ([".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"]
                .contains(ext)) {
              icon = Icons.image;
            } else if (ext == ".pdf") {
              icon = Icons.picture_as_pdf;
            } else if ([
              ".txt",
              ".md",
              ".csv",
              ".json",
              ".xml",
              ".docx",
              ".doc",
              ".xls",
              ".xlsx",
              ".ppt",
              ".pptx"
            ].contains(ext)) {
              icon = Icons.description;
            } else {
              icon = Icons.attach_file;
            }

            return ListTile(
              leading: Icon(icon, color: Colors.blueGrey),
              title: Text(
                fileName,
                maxLines: 1,
                textAlign: TextAlign.left,
                style: Theme.of(context).textTheme.bodyMedium,
              ),
              trailing: IconButton(
                icon: const Icon(Icons.download),
                tooltip: 'Télécharger le fichier',
                onPressed: () async {
                  if (await canLaunchUrl(Uri.parse(url))) {
                    await launchUrl(
                      Uri.parse(url),
                      mode: LaunchMode.externalApplication,
                    );
                  }
                },
              ),
              onTap: () async {
                if (await canLaunchUrl(Uri.parse(url))) {
                  // Pour les fichiers visualisables, utiliser différentes stratégies
                  if (_isViewableInBrowser(ext)) {
                    if ([".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"].contains(ext)) {
                      // Pour les images, afficher dans un dialog intégré
                      _showImageDialog(context, url, fileName);
                    } else if (ext == ".pdf") {
                      // Pour les PDFs, utiliser Google Docs Viewer
                      final viewerUrl = 'https://docs.google.com/viewer?url=${Uri.encodeComponent(url)}';
                      await launchUrl(
                        Uri.parse(viewerUrl),
                        mode: LaunchMode.platformDefault,
                      );
                    } else {
                      // Pour les autres fichiers texte, ouvrir directement
                      await launchUrl(
                        Uri.parse(url),
                        mode: LaunchMode.platformDefault,
                      );
                    }
                  } else {
                    // Pour les autres fichiers, télécharger directement
                    await launchUrl(
                      Uri.parse(url),
                      mode: LaunchMode.externalApplication,
                    );
                  }
                }
              },
              contentPadding: EdgeInsets.zero,
              dense: true,
            );
          }).toList(),
        ),
      ],
    );
  }

  bool _isViewableInBrowser(String ext) {
    // Extensions de fichiers qui peuvent être visualisées directement dans le navigateur
    return [
      ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", // Images
      ".pdf", // PDF
      ".txt", ".md", ".json", ".xml", ".csv" // Texte
    ].contains(ext);
  }

  void _showImageDialog(BuildContext context, String imageUrl, String fileName) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          child: SizedBox(
            width: MediaQuery.of(context).size.width * 0.9,
            height: MediaQuery.of(context).size.height * 0.8,
            child: Column(
              children: [
                // Header avec le nom du fichier
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: AppColors.rouge.withOpacity(0.1),
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          fileName,
                          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () => Navigator.of(context).pop(),
                      ),
                    ],
                  ),
                ),
                // Image qui prend tout l'espace disponible
                Expanded(
                  child: Container(
                    width: double.infinity,
                    padding: const EdgeInsets.all(8),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        imageUrl,
                        fit: BoxFit.contain,
                        width: double.infinity,
                        height: double.infinity,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return Center(
                            child: CircularProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                    loadingProgress.expectedTotalBytes!
                                  : null,
                            ),
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return const Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.error, size: 64, color: Colors.red),
                                Text('Erreur lors du chargement de l\'image'),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
