import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../services/error_service.dart';
import 'package:travel_mate/components/group/chat_group_content.dart';
import 'package:travel_mate/components/widgets/user_state_widget.dart';
import '../../blocs/user/user_bloc.dart';
import '../../blocs/user/user_state.dart' as user_state;
import '../../blocs/group/group_bloc.dart';
import '../../blocs/group/group_state.dart';
import '../../blocs/group/group_event.dart';
import '../../models/group.dart';

class GroupContent extends StatefulWidget {
  const GroupContent({super.key});

  @override
  State<GroupContent> createState() => _GroupContentState();
}

class _GroupContentState extends State<GroupContent> {
  @override
  void initState() {
    super.initState();

    // Charger immédiatement sans attendre le prochain frame
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
  }

  void _loadInitialData() {
    try {
      final userState = context.read<UserBloc>().state;

      if (userState is user_state.UserLoaded) {
        final userId = userState.user.id;
        context.read<GroupBloc>().add(LoadGroupsByUserId(userId));
      } else {
        throw Exception('Utilisateur non connecté');
      }
    } catch (e) {
      _buildErrorState(e.toString(), '', true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return UserStateWrapper(
      builder: (context, user) {
        return BlocConsumer<GroupBloc, GroupState>(
          listener: (context, groupState) {
            if (groupState is GroupOperationSuccess) {
              ErrorService().showSnackbar(
                message: groupState.message,
                isError: false,
              );
            } else if (groupState is GroupError) {
              ErrorService().showError(message: groupState.message);
            }
          },
          builder: (context, groupState) {
            return Scaffold(
              body: SafeArea(child: _buildContent(groupState, user.id)),
            );
          },
        );
      },
    );
  }

  Widget _buildContent(GroupState groupState, String userId) {
    if (groupState is GroupLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('Chargement des groupes...'),
          ],
        ),
      );
    }

    if (groupState is GroupError) {
      return _buildErrorState(groupState.message, userId, true);
    }

    if (groupState is GroupsLoaded) {
      if (groupState.groups.isEmpty) {
        return _buildEmptyState();
      }

      return _buildGroupsList(groupState.groups, userId);
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('État inconnu'),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              context.read<GroupBloc>().add(LoadGroupsByUserId(userId));
            },
            child: const Text('Charger les groupes'),
          ),
        ],
      ),
    );
  }

  Widget _buildGroupsList(List<Group> groups, String userId) {
    return RefreshIndicator(
      onRefresh: () async {
        context.read<GroupBloc>().add(LoadGroupsByUserId(userId));
        await Future.delayed(const Duration(milliseconds: 500));
      },
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          ...groups.map((group) {
            return Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: _buildSimpleGroupCard(group),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildSimpleGroupCard(Group group) {
    try {
      final colors = [Colors.blue, Colors.purple, Colors.green, Colors.orange];
      final color = colors[group.name.hashCode.abs() % colors.length];

      // Membres de manière simple
      String memberInfo = '${group.memberIds.length} membre(s)';
      if (group.members.isNotEmpty) {
        final names = group.members.take(2).map((m) => m.firstName).join(', ');
        memberInfo += '\n$names';
      }

      return Card(
        elevation: 2,
        child: ListTile(
          leading: CircleAvatar(
            backgroundColor: color,
            child: const Icon(Icons.group, color: Colors.white),
          ),
          title: Text(
            group.name,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
          subtitle: Text(memberInfo),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {
            _openGroupChat(group);
          },
        ),
      );
    } catch (e) {
      return Card(
        color: Colors.red[100],
        child: const ListTile(
          leading: Icon(Icons.error, color: Colors.red),
          title: Text('Erreur d\'affichage'),
        ),
      );
    }
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.forum_outlined, size: 80, color: Colors.grey[400]),
            const SizedBox(height: 16),
            const Text(
              'Aucun groupe',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              'Les groupes sont créés automatiquement',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorState(String error, String userId, bool retry) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        if (retry) {
          if (userId == '') {
            ErrorService().showError(
              title: 'Erreur utilisateur',
              message: 'Utilisateur non connecté. Veuillez vous reconnecter.',
              icon: Icons.error,
              iconColor: Colors.red,
              onRetry: () {
                Navigator.of(context).popUntil((route) => route.isFirst);
              },
            );
          } else {
            ErrorService().showError(
              title: 'Erreur de chargement',
              message: error,
              icon: Icons.cloud_off,
              iconColor: Colors.orange,
              onRetry: () {
                context.read<GroupBloc>().add(LoadGroupsByUserId(userId));
              },
            );
          }
        } else {
          ErrorService().showError(
            title: 'Erreur',
            message: error,
            icon: Icons.error,
            iconColor: Colors.red,
          );
        }
      }
    });

    return const Center(child: CircularProgressIndicator());
  }

  void _openGroupChat(Group group) {
    try {
      // Navigation vers la page de chat
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => ChatGroupContent(group: group)),
      );
    } catch (e) {
      _buildErrorState(e.toString(), '', false);
    }
  }
}
