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

import '../../../../core/settings/app_settings.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/theme/ranks.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../../core/widgets/player_avatar.dart';
import '../../../../core/widgets/rank_badge.dart';
import '../../../wallet/presentation/bloc/wallet_bloc.dart';
import '../../../wallet/presentation/bloc/wallet_event.dart';
import '../../domain/entities/profile_entity.dart';
import '../bloc/profile_bloc.dart';
import '../bloc/profile_event.dart';
import '../bloc/profile_state.dart';
import '../bloc/profile_status.dart';

part 'profile_screen.parts.dart';

/// صفحه‌ی پروفایل: نام، آواتار (قابل ویرایش)، سطح، جام و آمارِ بازی (ویژه‌ی VIP).
class ProfileScreen extends StatelessWidget {
  const ProfileScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: SafeArea(
          child: BlocConsumer<ProfileBloc, ProfileBlocState>(
            listenWhen: (a, b) => a.saveStatus != b.saveStatus,
            listener: (context, state) {
              final s = state.saveStatus;
              if (s is ProfileSaveSuccess) {
                context.read<WalletBloc>().add(LoadWalletEvent());
              } else if (s is ProfileSaveError) {
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text(s.message)));
              }
            },
            builder: (context, state) {
              final st = state.loadStatus;
              if (st is ProfileLoadError) {
                return Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        st.message,
                        style: const TextStyle(color: Colors.white70),
                      ),
                      const SizedBox(height: 12),
                      GameButton(
                        label: 'تلاش دوباره',
                        onTap:
                            () => context.read<ProfileBloc>().add(
                              LoadProfileEvent(),
                            ),
                      ),
                    ],
                  ),
                );
              }
              if (st is! ProfileLoadLoaded) {
                return const Center(
                  child: CircularProgressIndicator(color: AppColors.gold),
                );
              }
              return _content(context, st.profile);
            },
          ),
        ),
      ),
    );
  }

  Future<void> _editProfile(BuildContext context, ProfileEntity d) async {
    final result = await showModalBottomSheet<Map<String, String>>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => _EditProfileSheet(name: d.name, avatar: d.avatar),
    );
    if (result == null || !context.mounted) return;
    context.read<ProfileBloc>().add(
      SaveProfileEvent(result['name']!, result['avatar']!),
    );
  }

  Widget _content(BuildContext context, ProfileEntity d) {
    return SingleChildScrollView(
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 28),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              const AppBackButton(),
              const Spacer(),
              const GlowText('پروفایل', size: 24),
              const Spacer(),
              const SizedBox(width: 48),
            ],
          ),
          const SizedBox(height: 12),
          _HeroCard(profile: d, onEdit: () => _editProfile(context, d)),
          const SizedBox(height: 14),
          _HighlightStrip(profile: d),
          const SizedBox(height: 20),
          _SectionHeader(icon: Icons.query_stats, title: 'آمار بازی'),
          const SizedBox(height: 10),
          _statsSection(context, d),
          const SizedBox(height: 20),
          _SectionHeader(icon: Icons.tune, title: 'تنظیمات'),
          const SizedBox(height: 10),
          const _GraphicsToggle(),
          const SizedBox(height: 10),
          _SettingsTile(
            icon: Icons.gavel,
            label: 'شرایط و قوانین',
            onTap: () => context.push('/terms'),
          ),
        ],
      ),
    );
  }

  Widget _statsSection(BuildContext context, ProfileEntity d) {
    final s = d.stats;
    final rate =
        (s != null && s.games > 0)
            ? '${(s.wins * 100 / s.games).round()}٪'
            : '—';
    final tiles = <Widget>[
      _StatTile('نرخ برد', rate, Icons.percent, accent: true),
      _StatTile('بازی کل', '${s?.games ?? '—'}', Icons.casino),
      _StatTile('برد', '${s?.wins ?? '—'}', Icons.thumb_up),
      _StatTile('باخت', '${s?.losses ?? '—'}', Icons.thumb_down),
      _StatTile('کُت کردن', '${s?.kotMade ?? '—'}', Icons.flash_on),
      _StatTile('کُت شدن', '${s?.kotReceived ?? '—'}', Icons.flash_off),
      _StatTile('بریدن', '${s?.cuts ?? '—'}', Icons.bolt),
      _StatTile('دست حاکم', '${s?.hakemCount ?? '—'}', Icons.workspace_premium),
    ];
    final card = Container(
      padding: const EdgeInsets.all(10),
      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.goldFaint),
      ),
      child: GridView.count(
        crossAxisCount: 2,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        childAspectRatio: 2.5,
        children: tiles,
      ),
    );
    if (d.vip) return card;

    return Stack(
      children: [
        Opacity(opacity: 0.3, child: IgnorePointer(child: card)),
        Positioned.fill(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.5),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: AppColors.goldDark),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.lock, color: AppColors.gold, size: 34),
                const SizedBox(height: 8),
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24),
                  child: Text(
                    'مشاهده‌ی آمار ویژه‌ی کاربران VIP است',
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white, fontSize: 14),
                  ),
                ),
                const SizedBox(height: 12),
                GameButton(
                  label: 'تهیه اشتراک VIP',
                  icon: Icons.workspace_premium,
                  colors: const [Color(0xFFFFC107), AppColors.goldDark],
                  onTap: () async {
                    await context.push('/vip');
                    if (context.mounted) {
                      context.read<ProfileBloc>().add(LoadProfileEvent());
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
