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 '../../../../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/login_status.dart';

/// صفحه‌ی ورود شماره موبایل.
class MobileScreen extends StatefulWidget {
  const MobileScreen({super.key});

  @override
  State<MobileScreen> createState() => _MobileScreenState();
}

class _MobileScreenState extends State<MobileScreen> {
  final _controller = TextEditingController();

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

  bool get _valid => RegExp(r'^09\d{9}$').hasMatch(_controller.text.trim());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: BlocConsumer<AuthBloc, AuthState>(
          listenWhen: (a, b) => a.loginStatus != b.loginStatus,
          listener: (context, state) {
            final s = state.loginStatus;
            if (s is LoginSuccess) {
              context.push('/otp');
            } else if (s is LoginError) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text(s.message)));
            }
          },
          builder: (context, state) {
            final loading = state.loginStatus is LoginLoading;
            return Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const GlowText('حاکم ایرانی', size: 40),
                    const SizedBox(height: 28),
                    GamePanel(
                      padding: const EdgeInsets.all(22),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Text(
                            'برای ورود شماره موبایلت رو وارد کن',
                            style: TextStyle(color: Colors.white70),
                          ),
                          const SizedBox(height: 20),
                          TextField(
                            controller: _controller,
                            keyboardType: TextInputType.phone,
                            textAlign: TextAlign.center,
                            textDirection: TextDirection.ltr,
                            style: const TextStyle(
                              fontSize: 20,
                              letterSpacing: 2,
                            ),
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              LengthLimitingTextInputFormatter(11),
                            ],
                            decoration: const InputDecoration(
                              hintText: '09xxxxxxxxx',
                            ),
                            onChanged: (_) => setState(() {}),
                          ),
                          const SizedBox(height: 20),
                          GameButton(
                            label: 'دریافت کد',
                            width: double.infinity,
                            colors: const [
                              Color(0xFF3FA34D),
                              Color(0xFF1B5E20),
                            ],
                            onTap:
                                (!_valid || loading)
                                    ? null
                                    : () => context.read<AuthBloc>().add(
                                      LoginOtpEvent(_controller.text.trim()),
                                    ),
                          ),
                          const SizedBox(height: 8),
                          TextButton(
                            onPressed: () => context.push('/terms'),
                            child: const Text.rich(
                              TextSpan(
                                text: 'با ورود، ',
                                style: TextStyle(
                                    color: Colors.white54, fontSize: 12),
                                children: [
                                  TextSpan(
                                    text: 'شرایط و قوانین',
                                    style: TextStyle(
                                        color: AppColors.gold,
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  TextSpan(text: ' را می‌پذیرید'),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
