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

import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../auth/presentation/bloc/auth_bloc.dart';
import '../../../auth/presentation/bloc/auth_event.dart';
import '../../domain/entities/wallet_entity.dart';
import '../bloc/daily_status.dart';
import '../bloc/wallet_bloc.dart';
import '../bloc/wallet_event.dart';
import '../bloc/wallet_state.dart';
import '../bloc/wallet_status.dart';

/// لابی اصلی: کیف‌پول، دکمه بازی/دورهمی/فروشگاه/سکه روزانه.
class LobbyScreen extends StatefulWidget {
  const LobbyScreen({super.key});

  @override
  State<LobbyScreen> createState() => _LobbyScreenState();
}

class _LobbyScreenState extends State<LobbyScreen> {
  @override
  void initState() {
    super.initState();
    context.read<WalletBloc>().add(LoadWalletEvent());
  }

  void _reload() => context.read<WalletBloc>().add(LoadWalletEvent());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: BlocConsumer<WalletBloc, WalletBlocState>(
          listenWhen: (a, b) => a.dailyStatus != b.dailyStatus,
          listener: (context, state) {
            final d = state.dailyStatus;
            if (d is DailySuccess) {
              ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('سکه روزانه دریافت شد: +${d.amount}')));
            } else if (d is DailyError) {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text(d.message)));
            }
          },
          builder: (context, state) {
            final st = state.walletStatus;
            final wallet = st is WalletLoaded ? st.wallet : null;
            return Column(
              children: [
                _TopBar(wallet: wallet, onCoinTap: () => _openShop(context)),
                Expanded(
                  child: Center(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.symmetric(horizontal: 28),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const GlowText('سلطان حکم', size: 44),
                          const SizedBox(height: 44),
                          GameButton(
                            label: 'بازی',
                            icon: Icons.style,
                            width: double.infinity,
                            colors: const [Color(0xFFC2185B), Color(0xFF6A0D38)],
                            onTap: () async {
                              await context.push('/game/tiers');
                              if (context.mounted) _reload();
                            },
                          ),
                          const SizedBox(height: 16),
                          GameButton(
                            label: 'دورهمی',
                            icon: Icons.group_add,
                            width: double.infinity,
                            colors: const [Color(0xFF1565C0), Color(0xFF0A2E57)],
                            onTap: () async {
                              await context.push('/private');
                              if (context.mounted) _reload();
                            },
                          ),
                          const SizedBox(height: 16),
                          GameButton(
                            label: 'رتبه‌بندی',
                            icon: Icons.leaderboard,
                            width: double.infinity,
                            colors: const [Color(0xFFE9952F), Color(0xFF9C5A00)],
                            onTap: () => context.push('/leaderboard'),
                          ),
                          const SizedBox(height: 16),
                          GameButton(
                            label: 'فروشگاه',
                            icon: Icons.storefront,
                            width: double.infinity,
                            colors: const [Color(0xFF7B1FA2), Color(0xFF3E0A57)],
                            onTap: () => _openShop(context),
                          ),
                          const SizedBox(height: 16),
                          GameButton(
                            label: 'سکه روزانه',
                            icon: Icons.monetization_on,
                            width: double.infinity,
                            colors: const [AppColors.success, AppColors.successDark],
                            onTap: () =>
                                context.read<WalletBloc>().add(ClaimDailyEvent()),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                TextButton.icon(
                  onPressed: () {
                    context.read<AuthBloc>().add(LogoutEvent());
                    context.go('/login');
                  },
                  icon: const Icon(Icons.logout, color: Colors.white54),
                  label: const Text('خروج',
                      style: TextStyle(color: Colors.white54)),
                ),
                const SizedBox(height: 8),
              ],
            );
          },
        ),
      ),
    );
  }

  Future<void> _openShop(BuildContext context) async {
    await context.push('/shop');
    if (context.mounted) _reload();
  }
}

class _TopBar extends StatelessWidget {
  final WalletEntity? wallet;
  final VoidCallback onCoinTap;
  const _TopBar({required this.wallet, required this.onCoinTap});

  @override
  Widget build(BuildContext context) {
    final w = wallet;
    return Container(
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [AppColors.bg, AppColors.bgDark],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColors.goldDark),
        boxShadow: const [BoxShadow(color: Colors.black54, blurRadius: 8)],
      ),
      child: Row(
        children: [
          GestureDetector(
            onTap: () async {
              await context.push('/profile');
              if (context.mounted) {
                context.read<WalletBloc>().add(LoadWalletEvent());
              }
            },
            child: Container(
              width: 48,
              height: 48,
              padding: const EdgeInsets.all(2),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: AppColors.panel,
                border: Border.all(color: AppColors.gold, width: 2),
              ),
              child: (w == null || w.avatar.isEmpty)
                  ? const Icon(Icons.person, color: AppColors.gold)
                  : ClipOval(child: RandomAvatar(w.avatar)),
            ),
          ),
          const SizedBox(width: 10),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(children: [
                if (w != null && w.name.isNotEmpty) ...[
                  Text(w.name,
                      style: const TextStyle(
                          color: Colors.white, fontWeight: FontWeight.bold)),
                  const SizedBox(width: 6),
                ],
                if (w?.vip == true) const _VipTag(),
              ]),
              const SizedBox(height: 2),
              Row(children: [
                const Icon(Icons.star, color: AppColors.gold, size: 16),
                const SizedBox(width: 4),
                Text('سطح ${w?.level ?? '-'}',
                    style: const TextStyle(
                        color: AppColors.gold, fontWeight: FontWeight.bold)),
              ]),
              const SizedBox(height: 4),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: SizedBox(
                  width: 96,
                  height: 7,
                  child: LinearProgressIndicator(
                    value: (w == null || w.xpForNext == 0)
                        ? 0
                        : w.xpIntoLevel / w.xpForNext,
                    backgroundColor: Colors.white10,
                    valueColor: const AlwaysStoppedAnimation(AppColors.gold),
                  ),
                ),
              ),
            ],
          ),
          const Spacer(),
          GestureDetector(
            onTap: onCoinTap,
            child: StatChip(
                icon: Icons.confirmation_number, value: '${w?.tickets ?? 0}'),
          ),
          const SizedBox(width: 8),
          GestureDetector(
            onTap: onCoinTap,
            child: StatChip(
                icon: Icons.monetization_on, value: '${w?.coins ?? 0}'),
          ),
        ],
      ),
    );
  }
}

class _VipTag extends StatelessWidget {
  const _VipTag();
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
            colors: [Color(0xFFFFD54F), AppColors.goldDark]),
        borderRadius: BorderRadius.circular(6),
      ),
      child: const Text('VIP',
          style: TextStyle(
              color: AppColors.bg,
              fontWeight: FontWeight.bold,
              fontSize: 10)),
    );
  }
}
