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

import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../wallet/presentation/bloc/wallet_bloc.dart';
import '../../../wallet/presentation/bloc/wallet_event.dart';
import '../../../wallet/presentation/bloc/wallet_status.dart';
import '../bloc/shop_bloc.dart';
import '../bloc/shop_event.dart';
import '../bloc/shop_state.dart';
import '../bloc/shop_status.dart';

/// صفحه‌ی اشتراک VIP: نمایش بسته‌ها و خرید.
class VipScreen extends StatelessWidget {
  const VipScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: SafeArea(
          child: BlocConsumer<ShopBloc, ShopBlocState>(
            listenWhen: (a, b) => a.actionStatus != b.actionStatus,
            listener: (context, state) {
              final s = state.actionStatus;
              if (s is ActionSuccess) {
                context.read<WalletBloc>().add(LoadWalletEvent());
                ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text(s.message)));
              } else if (s is ActionError) {
                ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text(s.message)));
              }
            },
            builder: (context, state) {
              final st = state.loadStatus;
              if (st is ShopLoadError) {
                return Center(
                  child: Column(mainAxisSize: MainAxisSize.min, children: [
                    Text(st.message,
                        style: const TextStyle(color: Colors.white70)),
                    TextButton(
                        onPressed: () =>
                            context.read<ShopBloc>().add(LoadShopEvent()),
                        child: const Text('تلاش مجدد')),
                  ]),
                );
              }
              if (st is! ShopLoaded) {
                return const Center(
                    child: CircularProgressIndicator(color: AppColors.gold));
              }
              final packages = st.data.vipPackages;
              final isVip = context.select((WalletBloc c) {
                final ws = c.state.walletStatus;
                return ws is WalletLoaded ? ws.wallet.vip : false;
              });
              return Column(
                children: [
                  Row(children: [
                    const AppBackButton(),
                    const Spacer(),
                    const GlowText('اشتراک VIP', size: 24),
                    const Spacer(),
                    const SizedBox(width: 48),
                  ]),
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(14),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(colors: [
                                Color(0xFF5A3A00),
                                Color(0xFF2A1A00)
                              ]),
                              borderRadius: BorderRadius.circular(14),
                              border:
                                  Border.all(color: AppColors.gold, width: 1.3),
                            ),
                            child: Column(children: [
                              const Icon(Icons.workspace_premium,
                                  color: AppColors.gold, size: 40),
                              const SizedBox(height: 6),
                              Text(
                                  isVip
                                      ? 'شما کاربر VIP هستید'
                                      : 'با VIP بازی حرفه‌ای‌تری داشته باش',
                                  style: const TextStyle(
                                      color: AppColors.gold,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16)),
                              const SizedBox(height: 10),
                              const _Benefit('میزهای خصوصی نامحدود'),
                              const _Benefit('مشاهده‌ی کامل آمار بازی'),
                              const _Benefit('۱۰٪ سکه‌ی هدیه در هر خرید'),
                            ]),
                          ),
                          const SizedBox(height: 18),
                          for (final p in packages)
                            Padding(
                              padding: const EdgeInsets.only(bottom: 12),
                              child: _VipPackageTile(
                                title: p.title,
                                months: p.months,
                                price: p.priceToman,
                                busy: state.busy,
                                onBuy: () => context
                                    .read<ShopBloc>()
                                    .add(PurchaseEvent('vip', p.id, sku: p.sku)),
                              ),
                            ),
                          if (packages.isEmpty)
                            const Padding(
                              padding: EdgeInsets.only(top: 30),
                              child: Text('فعلاً بسته‌ای موجود نیست',
                                  style: TextStyle(color: Colors.white54)),
                            ),
                        ],
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}

class _VipPackageTile extends StatelessWidget {
  final String title;
  final int months;
  final int price;
  final bool busy;
  final VoidCallback onBuy;
  const _VipPackageTile({
    required this.title,
    required this.months,
    required this.price,
    required this.busy,
    required this.onBuy,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [AppColors.lapisHi, AppColors.lapisLo],
        ),
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: AppColors.gold, width: 1.4),
      ),
      child: Row(children: [
        const Icon(Icons.workspace_premium, color: AppColors.gold, size: 34),
        const SizedBox(width: 12),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title,
                style: const TextStyle(
                    color: AppColors.gold,
                    fontWeight: FontWeight.bold,
                    fontSize: 16)),
            Text('$months ماه اشتراک',
                style: const TextStyle(color: Colors.white70, fontSize: 12)),
          ],
        ),
        const Spacer(),
        GameButton(label: '$price تومان', onTap: busy ? null : onBuy),
      ]),
    );
  }
}

class _Benefit extends StatelessWidget {
  final String text;
  const _Benefit(this.text);
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(children: [
        const Icon(Icons.check_circle, color: Color(0xFF6FCF7A), size: 16),
        const SizedBox(width: 6),
        Expanded(
            child: Text(text,
                style: const TextStyle(color: Colors.white, fontSize: 13))),
      ]),
    );
  }
}
