import 'package:flutter/material.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:em2rp/services/pdf_service.dart';
import 'package:printing/printing.dart';

/// Widget réutilisable pour sélectionner le format de génération de QR codes multiples
/// Compatible avec n'importe quel type d'objet (équipements, conteneurs, etc.)
class QRCodeFormatSelectorDialog<T> extends StatelessWidget {
  final List<T> itemList;
  final String Function(T) getId;
  final String Function(T) getTitle;
  final List<String> Function(T)? getDetails;
  final String dialogTitle;

  const QRCodeFormatSelectorDialog({
    super.key,
    required this.itemList,
    required this.getId,
    required this.getTitle,
    this.getDetails,
    required this.dialogTitle,
  });

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        padding: const EdgeInsets.all(24),
        constraints: const BoxConstraints(maxWidth: 600, maxHeight: 700),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // En-tête
            Row(
              children: [
                const Icon(Icons.qr_code_2, color: AppColors.rouge, size: 32),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    dialogTitle,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            const SizedBox(height: 24),
            const Text(
              'Choisissez un format d\'étiquette :',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            ),
            const SizedBox(height: 16),

            // Liste des items
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey[300]!),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: ListView.separated(
                  shrinkWrap: true,
                  itemCount: itemList.length,
                  separatorBuilder: (context, index) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final item = itemList[index];
                    return ListTile(
                      dense: true,
                      leading: const Icon(Icons.qr_code, size: 20),
                      title: Text(
                        getId(item),
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      subtitle: Text(
                        getTitle(item),
                        style: const TextStyle(fontSize: 12),
                      ),
                    );
                  },
                ),
              ),
            ),
            const SizedBox(height: 24),

            // Boutons de format
            _FormatButton(
              icon: Icons.qr_code,
              title: 'Petits QR Codes',
              subtitle: 'QR codes compacts (2x2 cm)',
              onPressed: () => _generatePDF(context, itemList, QRLabelFormat.small),
            ),
            const SizedBox(height: 12),
            _FormatButton(
              icon: Icons.qr_code_2,
              title: 'QR Moyens',
              subtitle: 'QR codes taille moyenne (4x4 cm)',
              onPressed: () => _generatePDF(context, itemList, QRLabelFormat.medium),
            ),
            const SizedBox(height: 12),
            _FormatButton(
              icon: Icons.label,
              title: 'Grandes étiquettes',
              subtitle: 'QR + ID + Détails (10x5 cm)',
              onPressed: () => _generatePDF(context, itemList, QRLabelFormat.large),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _generatePDF(
    BuildContext context,
    List<T> items,
    QRLabelFormat format,
  ) async {
    // Capturer le navigator AVANT de fermer le premier dialog
    final navigator = Navigator.of(context);
    final scaffoldMessenger = ScaffoldMessenger.of(context);

    // Fermer le dialog de sélection
    navigator.pop();

    // Attendre un court instant pour que le dialog se ferme complètement
    await Future.delayed(const Duration(milliseconds: 100));

    // Afficher le dialogue de chargement
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (dialogContext) => Dialog(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppColors.rouge),
              ),
              const SizedBox(height: 20),
              const Text(
                'Génération du PDF en cours...',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                'Génération de ${items.length} QR code(s)',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );

    try {
      // Attendre que le dialog de chargement s'affiche complètement
      await Future.delayed(const Duration(milliseconds: 300));

      // Génération du PDF
      final pdfBytes = await PDFService.generatePDF<T>(
        items: items,
        format: format,
        getId: getId,
        getTitle: getTitle,
        getDetails: getDetails,
      );

      // Fermer le dialogue de chargement avec le navigator capturé
      navigator.pop();

      // Petite pause pour s'assurer que le dialog est bien fermé
      await Future.delayed(const Duration(milliseconds: 100));

      // Afficher le PDF
      await Printing.layoutPdf(
        onLayout: (format) async => pdfBytes,
        name: 'QRCodes_${DateTime.now().millisecondsSinceEpoch}.pdf',
      );

      scaffoldMessenger.showSnackBar(
        const SnackBar(
          content: Text('PDF généré avec succès'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      // Fermer le dialogue de chargement en cas d'erreur
      navigator.pop();

      scaffoldMessenger.showSnackBar(
        SnackBar(
          content: Text('Erreur lors de la génération du PDF: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}

/// Bouton de sélection de format
class _FormatButton extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final VoidCallback onPressed;

  const _FormatButton({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[300]!),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Icon(icon, color: AppColors.rouge, size: 32),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 13,
                    ),
                  ),
                ],
              ),
            ),
            const Icon(Icons.arrow_forward_ios, size: 16),
          ],
        ),
      ),
    );
  }
}

