import 'package:flutter/material.dart';
import 'package:em2rp/models/container_model.dart';
import 'package:em2rp/services/container_equipment_service.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:em2rp/views/container_detail_page.dart';

/// Widget pour afficher les containers qui référencent un équipement
/// Utilise le nouveau système : interroge Firestore via Cloud Function
class EquipmentReferencingContainers extends StatelessWidget {
  final String equipmentId;

  const EquipmentReferencingContainers({
    super.key,
    required this.equipmentId,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<ContainerModel>>(
      future: containerEquipmentService.getContainersByEquipment(equipmentId),
      builder: (context, snapshot) {
        // Ne rien afficher si vide et pas en chargement
        if (snapshot.connectionState == ConnectionState.done &&
            (!snapshot.hasData || snapshot.data!.isEmpty)) {
          return const SizedBox.shrink();
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Card(
            elevation: 2,
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Center(
                child: CircularProgressIndicator(),
              ),
            ),
          );
        }

        if (snapshot.hasError) {
          return const SizedBox.shrink(); // Masquer en cas d'erreur
        }

        final containers = snapshot.data ?? [];

        return Card(
          elevation: 2,
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Icon(Icons.inventory_2, color: AppColors.rouge),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'Boîtes contenant cet équipement (${containers.length})',
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                    ),
                  ],
                ),
                const Divider(height: 24),
                _buildContainersGrid(context, containers),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildContainersGrid(BuildContext context, List<ContainerModel> containers) {
    return Column(
      children: containers.map((container) {
        return _buildContainerCard(context, container);
      }).toList(),
    );
  }

  Widget _buildContainerCard(BuildContext context, ContainerModel container) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 1,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(color: Colors.grey.shade200, width: 1),
      ),
      child: InkWell(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (_) => ContainerDetailPage(container: container),
            ),
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              // Icône du type de container
              CircleAvatar(
                backgroundColor: AppColors.rouge.withValues(alpha: 0.1),
                radius: 28,
                child: container.type.getIconForAvatar(
                  size: 28,
                  color: AppColors.rouge,
                ),
              ),
              const SizedBox(width: 16),

              // Informations du container
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      container.name,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      container.type.label,
                      style: TextStyle(
                        fontSize: 13,
                        color: Colors.grey.shade600,
                      ),
                    ),
                    const SizedBox(height: 6),

                    // Badges d'information
                    Wrap(
                      spacing: 8,
                      runSpacing: 4,
                      children: [
                        _buildInfoChip(
                          icon: Icons.inventory,
                          label: '${container.itemCount} équipement${container.itemCount > 1 ? 's' : ''}',
                          color: Colors.blue,
                        ),
                        if (container.weight != null)
                          _buildInfoChip(
                            icon: Icons.scale,
                            label: '${container.weight!.toStringAsFixed(1)} kg',
                            color: Colors.orange,
                          ),
                        _buildInfoChip(
                          icon: Icons.tag,
                          label: container.id,
                          color: Colors.grey,
                          isCompact: true,
                        ),
                      ],
                    ),
                  ],
                ),
              ),

              // Icône de navigation
              Icon(
                Icons.chevron_right,
                color: AppColors.rouge,
                size: 28,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoChip({
    required IconData icon,
    required String label,
    required Color color,
    bool isCompact = false,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: isCompact ? 6 : 8,
        vertical: isCompact ? 2 : 4,
      ),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: color.withValues(alpha: 0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: isCompact ? 12 : 14,
            color: color.withValues(alpha: 0.8),
          ),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: isCompact ? 10 : 12,
              fontWeight: FontWeight.w600,
              color: color.withValues(alpha: 0.9),
            ),
          ),
        ],
      ),
    );
  }
}
