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';

/// Widget pour afficher les événements EN COURS utilisant cet équipement
class EquipmentCurrentEventsSection extends StatefulWidget {
  final EquipmentModel equipment;

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

  @override
  State<EquipmentCurrentEventsSection> createState() =>
      _EquipmentCurrentEventsSectionState();
}

class _EquipmentCurrentEventsSectionState
    extends State<EquipmentCurrentEventsSection> {
  final DataService _dataService = DataService(FirebaseFunctionsApiService());
  List<EventModel> _events = [];
  bool _isLoading = true;

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

  Future<void> _loadCurrentEvents() 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('[EquipmentCurrentEventsSection] Error parsing container ${containerData['id']}', e);
          }
        }
      }

      // Filtrer les événements en cours
      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) {
            // 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) {
              events.add(event);
            }
          }
        } catch (e) {
          DebugLog.error('[EquipmentCurrentEventsSection] Error parsing event $eventData', e);
        }
      }

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

      if (mounted) {
        setState(() {
          _events = events;
          _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,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // Ne rien afficher si pas d'événements en cours
    if (!_isLoading && _events.isEmpty) {
      return const SizedBox.shrink();
    }

    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // En-tête
            Row(
              children: [
                const Icon(Icons.play_circle, color: AppColors.rouge),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Événements en cours utilisant ce matériel',
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                ),
              ],
            ),
            const Divider(height: 24),

            // Liste des événements
            if (_isLoading)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(32.0),
                  child: CircularProgressIndicator(),
                ),
              )
            else
              Column(
                children: _events.map((event) => _buildEventCard(event)).toList(),
              ),
          ],
        ),
      ),
    );
  }

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

    // 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: const BorderSide(color: AppColors.rouge, width: 2),
      ),
      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,
                      ),
                    ),
                  ),
                  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,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

