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

/// Widget pour afficher les boîtes contenant un équipement
/// Utilise le nouveau système : interroge Firestore via Cloud Function
class EquipmentParentContainers extends StatelessWidget {
  final String equipmentId;

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<ContainerModel>>(
      future: containerEquipmentService.getContainersByEquipment(equipmentId),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Card(
            child: Padding(
              padding: EdgeInsets.all(16.0),
              child: Center(
                child: CircularProgressIndicator(),
              ),
            ),
          );
        }

        if (snapshot.hasError) {
          return Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                children: [
                  Icon(Icons.error_outline, color: Colors.red.shade700),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      'Erreur lors du chargement des boîtes',
                      style: TextStyle(color: Colors.red.shade700),
                    ),
                  ),
                ],
              ),
            ),
          );
        }

        final containers = snapshot.data ?? [];

        if (containers.isEmpty) {
          return Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                children: [
                  Icon(Icons.info_outline, color: Colors.grey.shade600),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      'Cet équipement n\'est dans aucune boîte',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
          );
        }

        return Card(
          elevation: 2,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Icon(Icons.inventory_2, color: AppColors.rouge, size: 20),
                    const SizedBox(width: 8),
                    Text(
                      'Boîtes contenant cet équipement (${containers.length})',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                ...containers.map((container) => _buildContainerCard(context, container)),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildContainerCard(BuildContext context, ContainerModel container) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Material(
        elevation: 1,
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ContainerDetailPage(container: container),
              ),
            );
          },
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade300),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              children: [
                // Icône du type de container
                CircleAvatar(
                  backgroundColor: AppColors.rouge.withValues(alpha: 0.1),
                  radius: 24,
                  child: container.type.getIconForAvatar(
                    size: 24,
                    color: AppColors.rouge,
                  ),
                ),
                const SizedBox(width: 12),

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

                      // Badges
                      Wrap(
                        spacing: 6,
                        runSpacing: 4,
                        children: [
                          _buildInfoChip(
                            icon: Icons.inventory,
                            label: '${container.itemCount} équip.',
                            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: Colors.grey.shade400),
              ],
            ),
          ),
        ),
      ),
    );
  }

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