import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import '../../../core/di/injection.dart'; import '../../../core/network/api_client.dart'; import '../../../core/theme/app_colors.dart'; import '../../../l10n/app_strings.dart'; import '../../../shared/widgets/app_snackbar.dart'; import '../../../shared/widgets/pred_button.dart'; import '../../../shared/widgets/pred_card.dart'; import '../../../shared/widgets/pred_text_field.dart'; import '../../../shared/widgets/prediqo_logo.dart'; import '../../../shared/widgets/tloto_gradient_app_bar.dart'; import '../../welcome/utils/welcome_navigation.dart'; import '../bloc/auth_bloc.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({super.key, this.showVerifyEmailHint = false}); final bool showVerifyEmailHint; @override State createState() => _LoginScreenState(); } class _LoginScreenState extends State { final _emailController = TextEditingController(); final _passwordController = TextEditingController(); final _totpController = TextEditingController(); final _mathAnswerController = TextEditingController(); bool _obscurePassword = true; /// Only kept on screen for EMAIL_NOT_VERIFIED (needs resend action). String? _verifyBanner; late bool _showVerifyHint; Timer? _bannerTimer; /// Local captcha UI state (survives AuthClearFeedback). /// Mobile always uses the signed math challenge (Turnstile WebView is unreliable). bool _captchaRequired = false; String? _mathPrompt; String? _mathChallengeToken; bool _mathChallengeLoading = false; @override void initState() { super.initState(); _showVerifyHint = widget.showVerifyEmailHint; if (_showVerifyHint) { _bannerTimer = scheduleMessageClear(setState, () { _showVerifyHint = false; }, duration: const Duration(seconds: 6)); } } @override void dispose() { _bannerTimer?.cancel(); _emailController.dispose(); _passwordController.dispose(); _totpController.dispose(); _mathAnswerController.dispose(); super.dispose(); } void _consumeFeedback() { context.read().add(const AuthClearFeedback()); } void _clearMathChallenge() { _mathPrompt = null; _mathChallengeToken = null; _mathAnswerController.clear(); } void _applyMathChallenge( Map? captcha, { bool allowRemoteFetch = true, }) { final provider = captcha?['provider']?.toString(); final prompt = captcha?['prompt']?.toString(); final token = captcha?['challengeToken']?.toString(); if (provider == 'math' && prompt != null && prompt.isNotEmpty && token != null && token.isNotEmpty) { setState(() { _captchaRequired = true; _mathChallengeLoading = false; _mathPrompt = prompt; _mathChallengeToken = token; _mathAnswerController.clear(); }); return; } // Turnstile (or empty) payload → fetch a signed math challenge for native. setState(() { _captchaRequired = true; _clearMathChallenge(); _mathChallengeLoading = allowRemoteFetch; }); if (allowRemoteFetch) { unawaited(_fetchMathChallenge()); } } Future _fetchMathChallenge() async { try { final res = await sl().dio.get>( '/api/v1/auth/captcha-challenge', queryParameters: const {'prefer': 'math'}, ); if (!mounted) return; _applyMathChallenge(res.data, allowRemoteFetch: false); if (_mathPrompt == null) { setState(() => _mathChallengeLoading = false); showErrorSnackBar(context, context.strings.captchaTurnstileUnavailable); } } catch (_) { if (!mounted) return; setState(() => _mathChallengeLoading = false); showErrorSnackBar(context, context.strings.captchaTurnstileUnavailable); } } String? _buildCaptchaToken() { if (!_captchaRequired) return null; final token = _mathChallengeToken; final answer = _mathAnswerController.text.trim(); if (token == null || token.isEmpty || answer.isEmpty) return null; return 'math:$token:$answer'; } void _submitLogin() { final bloc = context.read(); if (bloc.state.isSubmitting) return; final s = context.strings; final email = _emailController.text.trim(); final password = _passwordController.text; if (email.isEmpty || password.isEmpty) { showErrorSnackBar(context, s.loginFieldsRequired); return; } if (_captchaRequired && _mathChallengeLoading) { showErrorSnackBar(context, s.captchaMathHelper); return; } final captchaToken = _buildCaptchaToken(); if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) { showErrorSnackBar(context, s.captchaMathHelper); if (_mathPrompt == null) unawaited(_fetchMathChallenge()); return; } setState(() => _verifyBanner = null); bloc.add(AuthLoginRequested( email: email, password: password, totpCode: _totpController.text.isEmpty ? null : _totpController.text, captchaToken: captchaToken, )); } @override Widget build(BuildContext context) { final s = context.strings; final isDark = Theme.of(context).brightness == Brightness.dark; final bottomInset = MediaQuery.paddingOf(context).bottom; final keyboardInset = MediaQuery.viewInsetsOf(context).bottom; return AnnotatedRegion( value: TlotoGradientAppBar.overlayStyle, child: Scaffold( key: const Key('login_screen'), body: Column( children: [ TlotoGradientAppBar( title: s.signIn, showBack: true, backButtonKey: const Key('login_back'), onBack: () => popToWelcomeOrPrevious(context), ), Expanded( child: Center( child: SingleChildScrollView( padding: EdgeInsets.fromLTRB( 20, 16, 20, 24 + bottomInset + keyboardInset, ), child: BlocConsumer( listenWhen: (prev, curr) => prev.status != curr.status || prev.errorMessage != curr.errorMessage || prev.registerMessage != curr.registerMessage || prev.captcha != curr.captcha, listener: (context, state) { if (!isCurrentRoute(context)) return; if (state.status == AuthStatus.authenticated) { setState(() { _verifyBanner = null; _captchaRequired = false; _mathChallengeLoading = false; _clearMathChallenge(); }); _consumeFeedback(); context.go('/home'); return; } if (state.status == AuthStatus.verificationResent) { final msg = state.registerMessage ?? s.verificationEmailSent; setState(() { _verifyBanner = null; _showVerifyHint = true; }); _bannerTimer = scheduleMessageClear( setState, () => _showVerifyHint = false, duration: const Duration(seconds: 6), previous: _bannerTimer, ); showSuccessSnackBar(context, msg); _consumeFeedback(); return; } if (state.status == AuthStatus.error && state.errorMessage != null) { final msg = state.errorMessage! .replaceFirst('Exception: ', ''); // Only refresh the math challenge on captcha errors. // Other failures (wrong password/2FA) must keep the current prompt. if (state.isCaptchaChallenge) { _applyMathChallenge(state.captcha); } if (state.isEmailNotVerified) { setState(() => _verifyBanner = msg); _bannerTimer = scheduleMessageClear( setState, () => _verifyBanner = null, duration: const Duration(seconds: 8), previous: _bannerTimer, ); } else { setState(() => _verifyBanner = null); showErrorSnackBar(context, msg); } _consumeFeedback(); } }, builder: (context, state) { final loading = state.isSubmitting; return AutofillGroup( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ PredCard( gradient: AppColors.heroGradient(isDark), child: Column( children: [ const PrediqoLogo( size: 56, showWordmark: false, ), const SizedBox(height: 12), Text( s.appName, style: Theme.of(context) .textTheme .headlineMedium ?.copyWith(fontWeight: FontWeight.w800), ), const SizedBox(height: 6), Text( s.tagline, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodySmall, ), ], ), ) .animate() .fadeIn(duration: 400.ms) .slideY(begin: 0.05, end: 0), const SizedBox(height: 16), if (_showVerifyHint) ...[ PredCard( padding: const EdgeInsets.all(14), child: Text(s.registerSuccessVerify), ), const SizedBox(height: 12), ], if (_verifyBanner != null) ...[ PredCard( padding: const EdgeInsets.all(14), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Icon( Icons.error_outline, color: AppColors.danger, size: 20, ), const SizedBox(width: 10), Expanded( child: Text( _verifyBanner!, style: const TextStyle( color: AppColors.danger, fontWeight: FontWeight.w600, ), ), ), ], ), const SizedBox(height: 8), Text( s.emailNotVerifiedHint, style: Theme.of(context) .textTheme .bodySmall, ), TextButton( onPressed: loading ? null : () { final email = _emailController.text.trim(); if (email.isEmpty) { showErrorSnackBar( context, s.emailCannotBeEmpty, ); return; } context.read().add( AuthResendVerificationRequested( email, ), ); }, child: Text(s.resendVerification), ), ], ), ), const SizedBox(height: 12), ], PredCard( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ PredTextField( key: const Key('login_email'), controller: _emailController, label: s.email, keyboardType: TextInputType.emailAddress, prefixIcon: Icons.email_outlined, enabled: !loading, textInputAction: TextInputAction.next, autofillHints: const [AutofillHints.email], ), const SizedBox(height: 14), PredTextField( key: const Key('login_password'), controller: _passwordController, label: s.password, obscure: _obscurePassword, prefixIcon: Icons.lock_outline, enabled: !loading, textInputAction: TextInputAction.next, autofillHints: const [ AutofillHints.password ], suffix: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined, ), onPressed: loading ? null : () => setState( () => _obscurePassword = !_obscurePassword, ), ), ), const SizedBox(height: 14), PredTextField( controller: _totpController, label: s.totpCode, keyboardType: TextInputType.number, prefixIcon: Icons.security_outlined, maxLength: 6, enabled: !loading, textInputAction: _captchaRequired ? TextInputAction.next : TextInputAction.done, onSubmitted: loading ? null : (_) => _submitLogin(), ), if (_captchaRequired && _mathChallengeLoading) ...[ const SizedBox(height: 14), const Center( child: SizedBox( width: 22, height: 22, child: CircularProgressIndicator( strokeWidth: 2, ), ), ), ], if (_captchaRequired && !_mathChallengeLoading && _mathPrompt != null) ...[ const SizedBox(height: 14), PredTextField( key: const Key('login_captcha_math'), controller: _mathAnswerController, label: s.captchaMathLabel(_mathPrompt!), keyboardType: TextInputType.number, prefixIcon: Icons.verified_user_outlined, enabled: !loading, textInputAction: TextInputAction.done, onSubmitted: loading ? null : (_) => _submitLogin(), ), const SizedBox(height: 4), Text( s.captchaMathHelper, style: Theme.of(context) .textTheme .bodySmall, ), ], const SizedBox(height: 4), Align( alignment: Alignment.centerRight, child: TextButton( key: const Key('forgot_password_link'), onPressed: loading ? null : () => context .push('/forgot-password'), child: Text(s.forgotPassword), ), ), const SizedBox(height: 8), PredPrimaryButton( key: const Key('login_submit'), label: s.signIn, loading: loading, onPressed: _submitLogin, ), const SizedBox(height: 8), TextButton( onPressed: loading ? null : () => context.go('/register'), child: Text(s.signUp), ), ], ), ), ], ), ); }, ), ), ), ), ], ), ), ); } }