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

import '../../../../core/locator/locator.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../data/data_source/remote/tournament_api_provider.dart';
import '../../domain/entities/tournament.dart';

/// جدولِ رده‌بندیِ یک تورنومنت + خلاصه‌ی جوایز.
class TournamentStandingsScreen extends StatefulWidget {
  final Tournament tournament;
  const TournamentStandingsScreen({super.key, required this.tournament});

  @override
  State<TournamentStandingsScreen> createState() =>
      _TournamentStandingsScreenState();
}

class _TournamentStandingsScreenState extends State<TournamentStandingsScreen> {
  final _api = locator<TournamentApiProvider>();
  late Future<List<TournamentStanding>> _future;

  @override
  void initState() {
    super.initState();
    _future = _api.getStandings(widget.tournament.id);
  }

  @override
  Widget build(BuildContext context) {
    final t = widget.tournament;
    return Scaffold(
      body: GameBackground(
        child: SafeArea(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(12),
                child: Row(children: [
                  const AppBackButton(),
                  const Spacer(),
                  Flexible(child: GlowText(t.title, size: 20)),
                  const Spacer(),
                  const SizedBox(width: 48),
                ]),
              ),
              _prizeBar(t),
              Expanded(
                child: FutureBuilder<List<TournamentStanding>>(
                  future: _future,
                  builder: (context, snap) {
                    if (snap.connectionState != ConnectionState.done) {
                      return const Center(
                          child:
                              CircularProgressIndicator(color: AppColors.gold));
                    }
                    final rows = snap.data ?? const <TournamentStanding>[];
                    if (rows.isEmpty) {
                      return const Center(
                          child: Text('هنوز کسی امتیازی نگرفته است',
                              style: TextStyle(color: Colors.white54)));
                    }
                    return ListView.separated(
                      padding: const EdgeInsets.fromLTRB(14, 8, 14, 24),
                      itemCount: rows.length,
                      separatorBuilder: (_, __) => const SizedBox(height: 8),
                      itemBuilder: (_, i) => _row(rows[i]),
                    );
                  },
                ),
              ),
              // اگر تورنومنت فعال و کاربر ثبت‌نام کرده ⇒ راهِ مستقیم به بازی برای
              // کسبِ امتیاز (تا کاربر رابطه‌ی «بازی ⇒ امتیازِ تورنومنت» را حس کند).
              if (t.isActive && t.joined)
                Padding(
                  padding: const EdgeInsets.fromLTRB(14, 4, 14, 12),
                  child: GameButton(
                    label: 'بازی کن و امتیاز بگیر',
                    icon: Icons.sports_esports,
                    width: double.infinity,
                    colors: const [AppColors.gold, AppColors.goldDark],
                    onTap: () {
                      Navigator.of(context).pop(); // به لیستِ تورنومنت‌ها
                      context.push('/game/tiers');
                    },
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _prizeBar(Tournament t) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 14),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
      decoration: BoxDecoration(
        color: AppColors.gold.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.goldFaint),
      ),
      child: Row(children: [
        const Icon(Icons.emoji_events, color: AppColors.gold, size: 20),
        const SizedBox(width: 8),
        Text('جایزه کل: ${t.prizePool} سکه',
            style: const TextStyle(
                color: AppColors.gold, fontWeight: FontWeight.bold)),
        const Spacer(),
        if (t.prizes.isNotEmpty)
          Text(
            t.prizes
                .asMap()
                .entries
                .map((e) => '${e.key + 1}: ${e.value}')
                .join('  •  '),
            style: const TextStyle(color: Colors.white60, fontSize: 11),
          ),
      ]),
    );
  }

  Widget _row(TournamentStanding s) {
    final medal = s.rank <= 3;
    final medalColor = switch (s.rank) {
      1 => const Color(0xFFFFD700),
      2 => const Color(0xFFC0C0C0),
      3 => const Color(0xFFCD7F32),
      _ => Colors.transparent,
    };
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [AppColors.lapisHi, AppColors.lapisLo],
        ),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: medal ? medalColor : AppColors.goldFaint,
          width: medal ? 1.6 : 1,
        ),
      ),
      child: Row(children: [
        SizedBox(
          width: 30,
          child: medal
              ? Icon(Icons.emoji_events, color: medalColor, size: 22)
              : Text('${s.rank}',
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                      color: Colors.white70, fontWeight: FontWeight.bold)),
        ),
        const SizedBox(width: 6),
        ClipOval(
          child: SizedBox(
            width: 38,
            height: 38,
            child: RandomAvatar(s.avatarSeed),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(s.name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                      color: Colors.white, fontWeight: FontWeight.bold)),
              Text('${s.wins} برد • ${s.games} بازی',
                  style: const TextStyle(color: Colors.white54, fontSize: 11)),
            ],
          ),
        ),
        if (s.prize > 0) ...[
          Row(mainAxisSize: MainAxisSize.min, children: [
            const Icon(Icons.monetization_on, color: AppColors.gold, size: 15),
            const SizedBox(width: 3),
            Text('${s.prize}',
                style: const TextStyle(
                    color: AppColors.gold,
                    fontSize: 12,
                    fontWeight: FontWeight.bold)),
          ]),
          const SizedBox(width: 10),
        ],
        Column(children: [
          Text('${s.points}',
              style: const TextStyle(
                  color: AppColors.gold,
                  fontSize: 16,
                  fontWeight: FontWeight.bold)),
          const Text('امتیاز',
              style: TextStyle(color: Colors.white54, fontSize: 10)),
        ]),
      ]),
    );
  }
}
