import 'package:em2rp/utils/debug_log.dart';
import 'package:flutter/material.dart';
import 'package:em2rp/models/event_model.dart';
import 'package:em2rp/models/equipment_model.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';
import 'package:intl/intl.dart';

enum EventFilter {
  upcoming, // Événements à venir
  past,     // Événements passés
}

/// Widget pour afficher les événements associés à un équipement
class EquipmentAssociatedEventsSection extends StatefulWidget {
  final EquipmentModel equipment;

  const EquipmentAssociatedEventsSection({
    super.key,
    required this.equipment,
  });

  @override
  State<EquipmentAssociatedEventsSection> createState() =>
      _EquipmentAssociatedEventsSectionState();
}

class _EquipmentAssociatedEventsSectionState
    extends State<EquipmentAssociatedEventsSection> {
  final DataService _dataService = DataService(FirebaseFunctionsApiService());
  EventFilter _selectedFilter = EventFilter.upcoming;
  List<EventModel> _events = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadEvents();
  }

  Future<void> _loadEvents() async {
    if (mounted) {
      setState(() => _isLoading = true);
    }

    try {
      // Récupérer TOUS les événements via l'API
      final result = await _dataService.getEvents();
      final eventsData = result['events'] as List<dynamic>;

      final events = <EventModel>[];

      // Collecter tous les IDs de containers utilisés dans les événements
      final allContainerIds = <String>{};
      for (var eventData in eventsData) {
        final assignedContainers = eventData['assignedContainers'] as List<dynamic>? ?? [];
        allContainerIds.addAll(assignedContainers.map((id) => id.toString()));
      }

      // Charger SEULEMENT les containers utilisés (au lieu de TOUS les charger)
      final containersWithEquipment = <String>[];
      if (allContainerIds.isNotEmpty) {
        final containersData = await _dataService.getContainersByIds(allContainerIds.toList());

        for (var containerData in containersData) {
          try {
            final equipmentIds = List<String>.from(containerData['equipmentIds'] ?? []);

            if (equipmentIds.contains(widget.equipment.id)) {
              containersWithEquipment.add(containerData['id'] as String);
            }
          } catch (e) {
            DebugLog.error('[EquipmentAssociatedEventsSection] Error parsing container ${containerData['id']}', e);
          }
        }
      }

      // Filtrer manuellement les événements qui contiennent cet équipement
      for (var eventData in eventsData) {
        try {
          final event = EventModel.fromMap(eventData, eventData['id'] as String);

          // Vérifier si l'équipement est directement assigné
          final hasEquipmentDirectly = event.assignedEquipment.any(
            (eq) => eq.equipmentId == widget.equipment.id,
          );

          // Vérifier si l'équipement est dans une boîte assignée à l'événement
          final hasEquipmentInAssignedContainer = event.assignedContainers.any(
            (containerId) => containersWithEquipment.contains(containerId),
          );

          if (hasEquipmentDirectly || hasEquipmentInAssignedContainer) {
            events.add(event);
          }
        } catch (e) {
          DebugLog.error('[EquipmentAssociatedEventsSection] Error parsing event ${eventData['id']}', e);
        }
      }

      // Filtrer selon le statut
      final now = DateTime.now();
      final filteredEvents = events.where((event) {
        // Un événement est EN COURS dès que la préparation est complétée
        // et jusqu'à ce que le retour soit complété
        final isPrepared = event.preparationStatus == PreparationStatus.completed ||
            event.preparationStatus == PreparationStatus.completedWithMissing;

        final isReturned = event.returnStatus == ReturnStatus.completed ||
            event.returnStatus == ReturnStatus.completedWithMissing;

        final isInProgress = isPrepared && !isReturned;

        if (isInProgress) {
          return false; // Les événements en cours sont affichés dans une autre section
        }

        switch (_selectedFilter) {
          case EventFilter.upcoming:
            // Événements à venir = date de début dans le futur
            return event.startDateTime.isAfter(now);

          case EventFilter.past:
            // Événements passés = date de fin passée
            return event.endDateTime.isBefore(now);
        }
      }).toList();

      // Trier par date
      filteredEvents.sort((a, b) => a.startDateTime.compareTo(b.startDateTime));

      if (mounted) {
        setState(() {
          _events = filteredEvents;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
      }
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Erreur lors du chargement: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  String _getFilterLabel(EventFilter filter) {
    switch (filter) {
      case EventFilter.upcoming:
        return 'À venir';
      case EventFilter.past:
        return 'Passés';
    }
  }

  IconData _getFilterIcon(EventFilter filter) {
    switch (filter) {
      case EventFilter.upcoming:
        return Icons.upcoming;
      case EventFilter.past:
        return Icons.history;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // En-tête avec filtre
            Row(
              children: [
                const Icon(Icons.event, color: AppColors.rouge),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Événements passés / à venir',
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                ),
                // Menu déroulant pour filtrer
                PopupMenuButton<EventFilter>(
                  icon: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        _getFilterIcon(_selectedFilter),
                        size: 20,
                        color: AppColors.rouge,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        _getFilterLabel(_selectedFilter),
                        style: const TextStyle(
                          color: AppColors.rouge,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const Icon(Icons.arrow_drop_down, color: AppColors.rouge),
                    ],
                  ),
                  onSelected: (filter) {
                    if (mounted) {
                      setState(() => _selectedFilter = filter);
                    }
                    _loadEvents();
                  },
                  itemBuilder: (context) => EventFilter.values.map((filter) {
                    return PopupMenuItem(
                      value: filter,
                      child: Row(
                        children: [
                          Icon(_getFilterIcon(filter), size: 20),
                          const SizedBox(width: 8),
                          Text(_getFilterLabel(filter)),
                        ],
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
            const Divider(height: 24),

            // Liste des événements
            if (_isLoading)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(32.0),
                  child: CircularProgressIndicator(),
                ),
              )
            else if (_events.isEmpty)
              Padding(
                padding: const EdgeInsets.all(32.0),
                child: Center(
                  child: Column(
                    children: [
                      Icon(
                        Icons.event_busy,
                        size: 48,
                        color: Colors.grey.shade400,
                      ),
                      const SizedBox(height: 8),
                      Text(
                        'Aucun événement ${_getFilterLabel(_selectedFilter).toLowerCase()}',
                        style: TextStyle(
                          color: Colors.grey.shade600,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              Column(
                children: _events.map((event) => _buildEventCard(event)).toList(),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildEventCard(EventModel event) {
    final dateFormat = DateFormat('dd/MM/yyyy HH:mm');

    // Un événement est en cours dès que la préparation est complétée
    // et jusqu'à ce que le retour soit complété
    final isPrepared = event.preparationStatus == PreparationStatus.completed ||
        event.preparationStatus == PreparationStatus.completedWithMissing;

    final isReturned = event.returnStatus == ReturnStatus.completed ||
        event.returnStatus == ReturnStatus.completedWithMissing;

    final isInProgress = isPrepared && !isReturned;

    // Trouver la quantité utilisée pour les consommables/câbles
    int? usedQuantity;
    if (widget.equipment.hasQuantity) {
      final assignedEquipment = event.assignedEquipment.firstWhere(
        (eq) => eq.equipmentId == widget.equipment.id,
        orElse: () => EventEquipment(equipmentId: ''),
      );
      if (assignedEquipment.equipmentId.isNotEmpty) {
        usedQuantity = assignedEquipment.quantity;
      }
    }

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 1,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
        side: isInProgress
            ? const BorderSide(color: AppColors.rouge, width: 2)
            : BorderSide.none,
      ),
      child: InkWell(
        onTap: () {
          // Navigation vers les détails de l'événement si nécessaire
        },
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Titre de l'événement
              Row(
                children: [
                  Expanded(
                    child: Text(
                      event.name,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  if (isInProgress)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: AppColors.rouge,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Text(
                        'EN COURS',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 8),

              // Dates
              Row(
                children: [
                  const Icon(Icons.calendar_today, size: 14, color: Colors.grey),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      '${dateFormat.format(event.startDateTime)} → ${dateFormat.format(event.endDateTime)}',
                      style: TextStyle(
                        fontSize: 13,
                        color: Colors.grey.shade700,
                      ),
                    ),
                  ),
                ],
              ),

              // Quantité utilisée pour consommables/câbles
              if (usedQuantity != null) ...[
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.blue.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.blue),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Icon(Icons.inventory, size: 14, color: Colors.blue),
                      const SizedBox(width: 6),
                      Text(
                        'Quantité utilisée: $usedQuantity',
                        style: const TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue,
                        ),
                      ),
                    ],
                  ),
                ),
              ],

              const SizedBox(height: 8),

              // Statuts de préparation et retour
              Row(
                children: [
                  _buildStatusChip(
                    'Préparation',
                    event.preparationStatus ?? PreparationStatus.notStarted,
                  ),
                  const SizedBox(width: 8),
                  _buildStatusChip(
                    'Retour',
                    event.returnStatus ?? ReturnStatus.notStarted,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatusChip(String label, dynamic status) {
    Color color;
    String text;

    if (status is PreparationStatus) {
      switch (status) {
        case PreparationStatus.notStarted:
          color = Colors.grey;
          text = 'Non démarrée';
          break;
        case PreparationStatus.inProgress:
          color = Colors.orange;
          text = 'En cours';
          break;
        case PreparationStatus.completed:
          color = Colors.green;
          text = 'Complétée';
          break;
        case PreparationStatus.completedWithMissing:
          color = Colors.red;
          text = 'Manquants';
          break;
      }
    } else if (status is ReturnStatus) {
      switch (status) {
        case ReturnStatus.notStarted:
          color = Colors.grey;
          text = 'Non démarré';
          break;
        case ReturnStatus.inProgress:
          color = Colors.orange;
          text = 'En cours';
          break;
        case ReturnStatus.completed:
          color = Colors.green;
          text = 'Complété';
          break;
        case ReturnStatus.completedWithMissing:
          color = Colors.red;
          text = 'Manquants';
          break;
      }
    } else {
      color = Colors.grey;
      text = 'Inconnu';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '$label: ',
            style: TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          Text(
            text,
            style: TextStyle(
              fontSize: 11,
              color: color,
            ),
          ),
        ],
      ),
    );
  }
}

