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

import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../domain/entities/table_entities.dart';
import '../bloc/tier_bloc.dart';

/// لیست میزها (tierها) با ورودی/جایزه؛ انتخاب → ورود به میز.
class TierListScreen extends StatelessWidget {
  const TierListScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(12),
              child: Row(children: [
                const AppBackButton(),
                const Spacer(),
                const GlowText('انتخاب میز', size: 26),
                const Spacer(),
                const SizedBox(width: 48),
              ]),
            ),
            Expanded(
              child: BlocBuilder<TierBloc, TierState>(
                builder: (context, state) {
                  if (state is TierError) {
                    return Center(
                      child: Column(mainAxisSize: MainAxisSize.min, children: [
                        Text(state.message),
                        TextButton(
                          onPressed: () =>
                              context.read<TierBloc>().add(LoadTiersEvent()),
                          child: const Text('تلاش مجدد'),
                        ),
                      ]),
                    );
                  }
                  if (state is! TierLoaded) {
                    return const Center(
                        child:
                            CircularProgressIndicator(color: AppColors.gold));
                  }
                  final tiers = state.tiers;
                  return ListView.separated(
                    padding: const EdgeInsets.fromLTRB(16, 4, 16, 20),
                    itemCount: tiers.length + 1,
                    separatorBuilder: (_, __) => const SizedBox(height: 14),
                    itemBuilder: (_, i) {
                      if (i == 0) {
                        return Container(
                          margin: const EdgeInsets.only(bottom: 2),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 10),
                          decoration: BoxDecoration(
                            color: AppColors.gold.withValues(alpha: 0.1),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: AppColors.goldFaint),
                          ),
                          child: const Row(children: [
                            Icon(Icons.military_tech,
                                color: AppColors.gold, size: 18),
                            SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                'با بردن در هر میز، امتیازِ رتبه می‌گیرید و در جدولِ قهرمانان بالا می‌روید.',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 12.5),
                              ),
                            ),
                          ]),
                        );
                      }
                      final t = tiers[i - 1];
                      return _TierCard(tier: t, index: i - 1);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _TierCard extends StatelessWidget {
  final TableTier tier;
  final int index;
  const _TierCard({required this.tier, required this.index});

  static const _palettes = [
    [Color(0xFF43A047), AppColors.successDark],
    [Color(0xFFE53935), Color(0xFF8E0E1B)],
    [Color(0xFF1E88E5), Color(0xFF0D3C73)],
    [Color(0xFF8E24AA), Color(0xFF4A0D5E)],
  ];

  @override
  Widget build(BuildContext context) {
    final colors = _palettes[index % _palettes.length];
    return GestureDetector(
      onTap: () => context.push('/game/${tier.id}?prize=${tier.prize}'),
      child: Container(
        padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: colors,
          ),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.gold, width: 2),
          boxShadow: const [
            BoxShadow(
                color: Colors.black54, blurRadius: 10, offset: Offset(0, 5)),
          ],
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: const Color(0xFFE9952F),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: AppColors.gold),
              ),
              child: Column(children: [
                Text('${tier.hands}',
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold)),
                const Text('دست',
                    style: TextStyle(color: Colors.white, fontSize: 11)),
              ]),
            ),
            const SizedBox(width: 14),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(tier.title,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      shadows: [Shadow(color: Colors.black54, blurRadius: 3)],
                    )),
                const SizedBox(height: 6),
                _stat(Icons.login, 'ورودی', tier.entry),
                _stat(Icons.monetization_on, 'جایزه', tier.prize),
              ],
            ),
            const Spacer(),
            Column(children: [
              _badge(Icons.star, 'XP ${tier.xp}'),
              const SizedBox(height: 6),
              _badge(Icons.emoji_events, '${tier.trophy}'),
              if (tier.rankReward > 0) ...[
                const SizedBox(height: 6),
                _badge(Icons.military_tech, '+${tier.rankReward} رتبه'),
              ],
            ]),
          ],
        ),
      ),
    );
  }

  Widget _stat(IconData icon, String label, int value) => Padding(
        padding: const EdgeInsets.symmetric(vertical: 2),
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          Icon(icon, size: 15, color: AppColors.gold),
          const SizedBox(width: 5),
          Text('$label: $value',
              style: const TextStyle(color: Colors.white, fontSize: 13)),
        ]),
      );

  Widget _badge(IconData icon, String text) => Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: AppColors.gold),
          const SizedBox(width: 4),
          Text(text, style: const TextStyle(color: Colors.white, fontSize: 12)),
        ],
      );
}
