import 'package:flutter/material.dart';
import 'package:flutter/services.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 '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart';
import '../bloc/profile_status.dart';

/// صفحه‌ی انتخاب نام و آواتار پس از اولین ورود.
class ProfileSetupScreen extends StatefulWidget {
  const ProfileSetupScreen({super.key});

  @override
  State<ProfileSetupScreen> createState() => _ProfileSetupScreenState();
}

class _ProfileSetupScreenState extends State<ProfileSetupScreen> {
  final _name = TextEditingController();
  late List<String> _seeds;
  int _selected = 0;

  @override
  void initState() {
    super.initState();
    _seeds = List.generate(12, (i) => 'hakem-${i + 1}');
  }

  @override
  void dispose() {
    _name.dispose();
    super.dispose();
  }

  bool get _valid => _name.text.trim().length >= 2;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: BlocConsumer<AuthBloc, AuthState>(
          listenWhen: (a, b) => a.profileStatus != b.profileStatus,
          listener: (context, state) {
            final s = state.profileStatus;
            if (s is ProfileSuccess) {
              context.go('/lobby');
            } else if (s is ProfileError) {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text(s.message)));
            }
          },
          builder: (context, state) {
            final saving = state.profileStatus is ProfileLoading;
            return Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const GlowText('انتخاب نام و آواتار', size: 26),
                    const SizedBox(height: 20),
                    GamePanel(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            padding: const EdgeInsets.all(6),
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border:
                                  Border.all(color: AppColors.gold, width: 2),
                            ),
                            child: RandomAvatar(_seeds[_selected],
                                height: 84, width: 84),
                          ),
                          const SizedBox(height: 14),
                          TextField(
                            controller: _name,
                            textAlign: TextAlign.center,
                            maxLength: 20,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(20),
                            ],
                            decoration: const InputDecoration(
                                hintText: 'نام نمایشی (۲ تا ۲۰ حرف)',
                                counterText: ''),
                            onChanged: (_) => setState(() {}),
                          ),
                          const SizedBox(height: 14),
                          const Text('یک آواتار انتخاب کن',
                              style: TextStyle(color: AppColors.gold)),
                          const SizedBox(height: 10),
                          GridView.count(
                            crossAxisCount: 4,
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            mainAxisSpacing: 10,
                            crossAxisSpacing: 10,
                            children: [
                              for (var i = 0; i < _seeds.length; i++)
                                GestureDetector(
                                  onTap: () => setState(() => _selected = i),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: AppColors.bgDark,
                                      border: Border.all(
                                        color: _selected == i
                                            ? AppColors.gold
                                            : Colors.transparent,
                                        width: 2.5,
                                      ),
                                    ),
                                    child: RandomAvatar(_seeds[i]),
                                  ),
                                ),
                            ],
                          ),
                          const SizedBox(height: 18),
                          GameButton(
                            label: saving ? 'در حال ذخیره…' : 'تأیید و ورود',
                            width: double.infinity,
                            colors: const [AppColors.success, AppColors.successDark],
                            onTap: (!_valid || saving)
                                ? null
                                : () => context.read<AuthBloc>().add(
                                    UpdateProfileEvent(
                                        _name.text.trim(), _seeds[_selected])),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
