import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../data/providers/friends_provider.dart';
import 'cards/friend_card.dart';
import 'friends_empty_state.dart';
import 'friends_loading_state.dart';
import 'search_friends.dart';

/// Onglet affichant la liste des amis avec recherche et pagination.
class FriendsTab extends StatelessWidget {
  const FriendsTab({
    required this.userId,
    required this.scrollController,
    required this.onRefresh,
    super.key,
  });

  final String userId;
  final ScrollController scrollController;
  final VoidCallback onRefresh;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Column(
      children: [
        _buildSearchBar(),
        Expanded(
          child: Consumer<FriendsProvider>(
            builder: (context, provider, child) {
              if (provider.isLoading && provider.friendsList.isEmpty) {
                return FriendsLoadingState(theme: theme);
              }

              if (provider.friendsList.isEmpty) {
                return RefreshIndicator(
                  onRefresh: () async => onRefresh(),
                  color: theme.colorScheme.primary,
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    child: SizedBox(
                      height: MediaQuery.of(context).size.height - 300,
                      child: FriendsEmptyState(theme: theme),
                    ),
                  ),
                );
              }

              return _buildFriendsList(theme, provider);
            },
          ),
        ),
      ],
    );
  }

  /// Construit la barre de recherche.
  Widget _buildSearchBar() {
    return const Padding(
      padding: EdgeInsets.all(16),
      child: SearchFriends(),
    );
  }

  /// Construit la liste des amis.
  Widget _buildFriendsList(ThemeData theme, FriendsProvider provider) {
    return RefreshIndicator(
      onRefresh: () async => onRefresh(),
      color: theme.colorScheme.primary,
      child: GridView.builder(
        controller: scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(
          horizontal: 16,
          vertical: 8,
        ),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          childAspectRatio: 0.68,
        ),
        itemCount: provider.friendsList.length,
        itemBuilder: (context, index) {
          final friend = provider.friendsList[index];
          return FriendCard(friend: friend);
        },
      ),
    );
  }
}

