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

import '../../../../core/config.dart';
import '../../../../core/locator/locator.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/theme/frames.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../../core/widgets/player_avatar.dart';
import '../../../wallet/presentation/bloc/wallet_bloc.dart';
import '../../../wallet/presentation/bloc/wallet_event.dart';
import '../../../wallet/presentation/bloc/wallet_state.dart';
import '../../../wallet/presentation/bloc/wallet_status.dart';
import '../../data/data_source/remote/avatar_api_provider.dart';
import '../../data/data_source/remote/carpet_api_provider.dart';
import '../../data/data_source/remote/frame_api_provider.dart';
import '../../domain/entities/avatar_character.dart';
import '../../domain/entities/carpet.dart';
import '../../domain/entities/frame.dart';
import '../../domain/entities/shop_entities.dart';
import '../bloc/shop_bloc.dart';
import '../bloc/shop_event.dart';
import '../bloc/shop_state.dart';
import '../bloc/shop_status.dart';

part 'shop_screen.parts.dart';

/// فروشگاه با تب‌های سکه/بلیط/کارت/تجهیزات/VIP.
class ShopScreen extends StatelessWidget {
  const ShopScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 8,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: GameBackground(
          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) {
              return Column(
                children: [
                  _header(context),
                  Expanded(
                    child: Container(
                      margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [AppColors.lapisMid, AppColors.lapisLo],
                        ),
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(
                          color: AppColors.goldDark,
                          width: 1.5,
                        ),
                      ),
                      child: Column(
                        children: [
                          const _ShopTabs(),
                          Expanded(child: _body(context, state.loadStatus)),
                        ],
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _body(BuildContext context, ShopLoadStatus status) {
    if (status is ShopLoaded) {
      final d = status.data;
      return TabBarView(
        children: [
          _CoinsTab(packages: d.coinPackages),
          _TicketsTab(packages: d.ticketPackages),
          _CardsTab(data: d),
          const _AvatarsTab(),
          const _CarpetsTab(),
          const _FramesTab(),

          _BoostersTab(boosters: d.boosters),
          _VipTab(packages: d.vipPackages),
        ],
      );
    }
    if (status is ShopLoadError) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(status.message),
            TextButton(
              onPressed: () => context.read<ShopBloc>().add(LoadShopEvent()),
              child: const Text('تلاش مجدد'),
            ),
          ],
        ),
      );
    }
    return const Center(
      child: CircularProgressIndicator(color: AppColors.gold),
    );
  }

  Widget _header(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 8, 10, 6),
      child: Row(
        children: [
          const AppBackButton(),
          const Spacer(),
          const GlowText('فروشگاه', size: 24),
          const Spacer(),
          BlocBuilder<WalletBloc, WalletBlocState>(
            builder: (context, s) {
              final w =
                  s.walletStatus is WalletLoaded
                      ? (s.walletStatus as WalletLoaded).wallet
                      : null;
              return Row(
                children: [
                  _BalancePill(
                    icon: Icons.confirmation_number,
                    iconColor: const Color(0xFFC77DFF),
                    value: _fmt(w?.tickets ?? 0),
                  ),
                  const SizedBox(width: 8),
                  _BalancePill(
                    icon: Icons.monetization_on,
                    iconColor: AppColors.gold,
                    value: _fmt(w?.coins ?? 0),
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }
}
