import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:pinput/pinput.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/otp_status.dart';

/// صفحه‌ی ورود کد یک‌بارمصرف (۵ رقمی) با pinput و تکمیل خودکارِ پیامک.
class OtpScreen extends StatefulWidget {
  const OtpScreen({super.key});

  @override
  State<OtpScreen> createState() => _OtpScreenState();
}

class _OtpScreenState extends State<OtpScreen> {
  final _controller = TextEditingController();

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

  bool get _valid => _controller.text.trim().length == 5;

  void _submit(BuildContext context) {
    if (_valid) {
      context.read<AuthBloc>().add(CheckOtpEvent(_controller.text.trim()));
    }
  }

  @override
  Widget build(BuildContext context) {
    final defaultPin = PinTheme(
      width: 52,
      height: 60,
      textStyle: const TextStyle(
          color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
      decoration: BoxDecoration(
        color: AppColors.bgDark,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: AppColors.goldDark, width: 1.5),
      ),
    );

    return Scaffold(
      body: GameBackground(
        child: BlocConsumer<AuthBloc, AuthState>(
          listenWhen: (a, b) => a.otpStatus != b.otpStatus,
          listener: (context, state) {
            final s = state.otpStatus;
            if (s is OtpSuccess) {
              context.go(s.hasName ? '/lobby' : '/setup');
            } else if (s is OtpError) {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text(s.message)));
            }
          },
          builder: (context, state) {
            final loading = state.otpStatus is OtpLoading;
            return Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const GlowText('تأیید کد', size: 32),
                    const SizedBox(height: 24),
                    GamePanel(
                      padding: const EdgeInsets.all(22),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text('کد پیامک‌شده به ${state.mobile} را وارد کنید',
                              textAlign: TextAlign.center,
                              style: const TextStyle(color: Colors.white70)),
                          const SizedBox(height: 22),
                          Directionality(
                            textDirection: TextDirection.ltr,
                            child: Pinput(
                              length: 5,
                              controller: _controller,
                              autofocus: true,
                              keyboardType: TextInputType.number,
                              closeKeyboardWhenCompleted: true,
                              defaultPinTheme: defaultPin,
                              focusedPinTheme: defaultPin.copyWith(
                                decoration: defaultPin.decoration!.copyWith(
                                  border:
                                      Border.all(color: AppColors.gold, width: 2),
                                ),
                              ),
                              separatorBuilder: (_) => const SizedBox(width: 8),
                              pinAnimationType: PinAnimationType.fade,
                              // تکمیل خودکارِ کد از پیامک (Android: SMS User Consent).
                              androidSmsAutofillMethod:
                                  AndroidSmsAutofillMethod.smsUserConsentApi,
                              onChanged: (_) => setState(() {}),
                              onCompleted: (_) => _submit(context),
                            ),
                          ),
                          const SizedBox(height: 22),
                          GameButton(
                            label: 'ورود',
                            width: double.infinity,
                            colors: const [AppColors.success, AppColors.successDark],
                            onTap: (!_valid || loading)
                                ? null
                                : () => _submit(context),
                          ),
                          TextButton(
                            onPressed: loading ? null : () => context.pop(),
                            child: const Text('تغییر شماره',
                                style: TextStyle(color: AppColors.gold)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
