import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:slrpg_app/src/features/multiplayer/domain/entities/leaderboard_entry.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../data/repositories/leaderboard_repository.dart';
import '../../../gamification/domain/entities/avatar_config.dart';
import '../../../gamification/presentation/widgets/avatar_renderer.dart';

class LeaderboardScreen extends ConsumerStatefulWidget {
  const LeaderboardScreen({super.key});

  @override
  ConsumerState<LeaderboardScreen> createState() => _LeaderboardScreenState();
}

class _LeaderboardScreenState extends ConsumerState<LeaderboardScreen> {
  @override
  Widget build(BuildContext context) {
    final leaderboardAsync = ref.watch(leaderboardProvider);
    final currentUserAsync = ref.watch(userRepositoryProvider).getLocalUser();

    return Scaffold(
      appBar: AppBar(
        title: const Text('HALL OF FAME'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/hub'),
        ),
      ),
      body: leaderboardAsync.when(
        data: (entries) {
          return FutureBuilder(
              future: currentUserAsync,
              builder: (context, snapshot) {
                final currentUserId = snapshot.data?.serverId ?? '';

                return ListView.builder(
                  padding: const EdgeInsets.all(16),
                  itemCount: entries.length,
                  itemBuilder: (context, index) {
                    final entry = entries[index];
                    final isMe = entry.id == currentUserId;

                    return Card(
                      color: isMe
                          ? AppTheme.primaryColor.withValues(alpha: 0.1)
                          : null,
                      margin: const EdgeInsets.only(bottom: 8),
                      child: ListTile(
                        contentPadding: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 8),
                        leading: _buildRankBadge(entry.rank),
                        title: Text(
                          entry.name.isEmpty
                              ? 'Hero #${entry.id.substring(0, 5)}'
                              : entry.name,
                          style: TextStyle(
                            fontWeight:
                                isMe ? FontWeight.bold : FontWeight.normal,
                            color: isMe ? AppTheme.primaryColor : Colors.white,
                          ),
                        ),
                        subtitle: Text('Level ${entry.level} • ${entry.xp} XP'),
                        trailing: _buildAvatarPreview(entry),
                      ),
                    );
                  },
                );
              });
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text('Error: $err')),
      ),
    );
  }

  Widget _buildRankBadge(int rank) {
    Color color;
    double size = 24;

    switch (rank) {
      case 1:
        color = Colors.amber;
        size = 32;
        break;
      case 2:
        color = Colors.grey.shade400;
        size = 28;
        break;
      case 3:
        color = Colors.brown.shade400;
        size = 26;
        break;
      default:
        color = Colors.grey.shade700;
    }

    return SizedBox(
      width: 40,
      child: Center(
        child: rank <= 3
            ? Icon(Icons.emoji_events, color: color, size: size)
            : Text('#$rank',
                style: const TextStyle(
                    fontWeight: FontWeight.bold, color: Colors.grey)),
      ),
    );
  }

  Widget _buildAvatarPreview(LeaderboardEntry entry) {
    if (entry.avatar != null && entry.avatar!.isNotEmpty) {
      try {
        final config = AvatarConfig.fromJson(entry.avatar!);

        return SizedBox(
          width: 40,
          height: 40,
          child: AvatarRenderer(
            config: config,
            size: 40,
          ),
        );
      } catch (e) {}
    }
    return CircleAvatar(
      radius: 20,
      backgroundColor: Colors.grey.shade800,
      child: const Icon(Icons.person, color: Colors.white70),
    );
  }
}

final leaderboardProvider = FutureProvider((ref) async {
  return ref.read(leaderboardRepositoryProvider).getGlobalLeaderboard();
});
