import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:random_avatar/random_avatar.dart';

import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../../core/widgets/rank_badge.dart';
import '../../domain/entities/leaderboard.dart';
import '../bloc/leaderboard_bloc.dart';

/// جدولِ رتبه‌بندیِ فصل: برترین بازیکنان بر اساس امتیازِ رتبه.
class LeaderboardScreen extends StatelessWidget {
  const LeaderboardScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: SafeArea(
          child: Column(
            children: [
              Row(
                children: [
                  Padding(padding: EdgeInsets.all(10), child: AppBackButton()),
                  const Spacer(),
                  const GlowText('رتبه‌بندی فصل', size: 22),
                  const Spacer(),
                  const SizedBox(width: 48),
                ],
              ),
              Expanded(
                child: BlocBuilder<LeaderboardBloc, LeaderboardState>(
                  builder: (context, state) {
                    if (state is LeaderboardError) {
                      return Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              state.message,
                              style: const TextStyle(color: Colors.white70),
                            ),
                            TextButton(
                              onPressed:
                                  () => context.read<LeaderboardBloc>().add(
                                    LoadLeaderboardEvent(),
                                  ),
                              child: const Text('تلاش مجدد'),
                            ),
                          ],
                        ),
                      );
                    }
                    if (state is! LeaderboardLoaded) {
                      return const Center(
                        child: CircularProgressIndicator(color: AppColors.gold),
                      );
                    }
                    final lb = state.data;
                    if (lb.entries.isEmpty) {
                      return const Center(
                        child: Text(
                          'هنوز کسی در این فصل امتیاز نگرفته است',
                          style: TextStyle(color: Colors.white54),
                        ),
                      );
                    }
                    return Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.symmetric(vertical: 6),
                          child: Text(
                            'فصل ${lb.season}',
                            style: const TextStyle(
                              color: AppColors.gold,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        Expanded(
                          child: ListView.separated(
                            padding: const EdgeInsets.fromLTRB(12, 4, 12, 20),
                            itemCount: lb.entries.length,
                            separatorBuilder:
                                (_, __) => const SizedBox(height: 8),
                            itemBuilder: (_, i) => _row(lb.entries[i]),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _row(RankEntry e) {
    final medal = e.rank <= 3;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: [AppColors.lapis, AppColors.lapisHi]),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: medal ? AppColors.gold : AppColors.goldDark,
          width: medal ? 1.6 : 1,
        ),
      ),
      child: Row(
        children: [
          SizedBox(
            width: 28,
            child: Text(
              '${e.rank}',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: medal ? AppColors.gold : Colors.white70,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ),
          const SizedBox(width: 8),
          SizedBox(
            width: 40,
            height: 40,
            child: ClipOval(
              child: RandomAvatar(e.avatar.isEmpty ? e.name : e.avatar),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              e.name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: Colors.white, fontSize: 15),
            ),
          ),
          RankBadge(tier: e.tier, points: e.rankPoints, size: 13),
        ],
      ),
    );
  }
}
