import 'package:flutter/material.dart';
import 'package:geosector_app/core/theme/app_theme.dart';

/// Widget pour afficher la barre latérale des contacts
class ChatSidebar extends StatelessWidget {
  final List<Map<String, dynamic>> teamContacts;
  final List<Map<String, dynamic>> clientContacts;
  final bool isTeamChat;
  final int selectedContactId;
  final Function(int, String, bool) onContactSelected;
  final Function(bool) onToggleGroup;

  const ChatSidebar({
    super.key,
    required this.teamContacts,
    required this.clientContacts,
    required this.isTeamChat,
    required this.selectedContactId,
    required this.onContactSelected,
    required this.onToggleGroup,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // En-tête avec les onglets
        Container(
          padding: const EdgeInsets.all(AppTheme.spacingM),
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 5,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            children: [
              Expanded(
                child: _buildTabButton(
                  context,
                  'Équipe',
                  isTeamChat,
                  () => onToggleGroup(true),
                ),
              ),
              const SizedBox(width: AppTheme.spacingS),
              Expanded(
                child: _buildTabButton(
                  context,
                  'Clients',
                  !isTeamChat,
                  () => onToggleGroup(false),
                ),
              ),
            ],
          ),
        ),

        // Liste des contacts
        Expanded(
          child: Container(
            color: Colors.grey[100],
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                // Afficher les contacts appropriés en fonction de l'onglet sélectionné
                ...isTeamChat
                    ? teamContacts.map(
                        (contact) => _buildContactItem(context, contact, true))
                    : clientContacts.map((contact) =>
                        _buildContactItem(context, contact, false)),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // Construire un bouton d'onglet
  Widget _buildTabButton(
    BuildContext context,
    String label,
    bool isSelected,
    VoidCallback onPressed,
  ) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: isSelected ? AppTheme.primaryColor : Colors.grey[200],
        foregroundColor: isSelected ? Colors.white : Colors.black,
        elevation: isSelected ? 2 : 0,
        padding: const EdgeInsets.symmetric(vertical: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(AppTheme.borderRadiusSmall),
        ),
      ),
      child: Text(label),
    );
  }

  // Construire un élément de contact
  Widget _buildContactItem(
    BuildContext context,
    Map<String, dynamic> contact,
    bool isTeam,
  ) {
    final bool isSelected = contact['id'] == selectedContactId;
    final bool hasUnread = (contact['unread'] as int) > 0;

    return ListTile(
      selected: isSelected,
      selectedTileColor: Colors.blue.withOpacity(0.1),
      leading: CircleAvatar(
        backgroundColor: AppTheme.primaryColor.withOpacity(0.2),
        backgroundImage: contact['avatar'] != null
            ? AssetImage(contact['avatar'] as String)
            : null,
        child: contact['avatar'] == null
            ? Text(
                (contact['name'] as String).isNotEmpty
                    ? (contact['name'] as String)[0].toUpperCase()
                    : '',
                style: const TextStyle(
                  color: AppTheme.primaryColor,
                  fontWeight: FontWeight.bold,
                ),
              )
            : null,
      ),
      title: Row(
        children: [
          Expanded(
            child: Text(
              contact['name'] as String,
              style: TextStyle(
                fontWeight: hasUnread ? FontWeight.bold : FontWeight.normal,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          if (contact['online'] == true)
            Container(
              width: 8,
              height: 8,
              decoration: const BoxDecoration(
                color: Colors.green,
                shape: BoxShape.circle,
              ),
            ),
        ],
      ),
      subtitle: Text(
        contact['lastMessage'] as String,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontWeight: hasUnread ? FontWeight.bold : FontWeight.normal,
          color: hasUnread ? Colors.black87 : Colors.grey[600],
        ),
      ),
      trailing: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            _formatTime(contact['time'] as DateTime),
            style: TextStyle(
              fontSize: 12,
              color: hasUnread ? AppTheme.primaryColor : Colors.grey[500],
            ),
          ),
          const SizedBox(height: 4),
          if (hasUnread)
            Container(
              padding: const EdgeInsets.all(6),
              decoration: const BoxDecoration(
                color: AppTheme.primaryColor,
                shape: BoxShape.circle,
              ),
              child: Text(
                (contact['unread'] as int).toString(),
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
        ],
      ),
      onTap: () => onContactSelected(
        contact['id'] as int,
        contact['name'] as String,
        isTeam,
      ),
    );
  }

  // Formater l'heure du dernier message
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate = DateTime(time.year, time.month, time.day);

    if (messageDate == today) {
      return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    } else if (messageDate == yesterday) {
      return 'Hier';
    } else {
      return '${time.day}/${time.month}';
    }
  }
}
