games_app/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart

452 lines
17 KiB
Dart

/// Wallet presentation: in-app transfer to another user by email.
library;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/di/injection.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/amount_utils.dart';
import '../../../core/utils/coin_display.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/repositories.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/section_error.dart';
import '../bloc/wallet_bloc.dart';
import '../utils/money_confirm_preflight.dart';
/// Form to transfer balance to another registered user; requires TOTP and confirmation.
class TransferScreen extends StatefulWidget {
const TransferScreen({super.key});
@override
State<TransferScreen> createState() => _TransferScreenState();
}
/// Validates inputs, shows a confirmation dialog, and dispatches [WalletTransferRequested].
class _TransferScreenState extends State<TransferScreen> {
final _emailController = TextEditingController();
final _amountController = TextEditingController();
final _totpController = TextEditingController();
String? _selectedWalletType;
bool? _totpEnabled;
bool _requireWithdrawal2fa = true;
bool _submitting = false;
bool _confirming = false;
bool _securityFailed = false;
String? _localError;
bool get _needs2faSetup => _requireWithdrawal2fa && _totpEnabled == false;
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadSecurityContext();
}
Future<void> _loadSecurityContext({bool forceProfile = false}) async {
try {
final profile =
await sl<AuthRepository>().getProfile(force: forceProfile);
final health = await sl<HealthRepository>().getHealth();
if (!mounted) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = health.requireWithdrawal2fa;
_securityFailed = false;
});
} catch (_) {
if (!mounted) return;
setState(() {
_totpEnabled ??= false;
_securityFailed = true;
});
}
}
@override
void dispose() {
_emailController.dispose();
_amountController.dispose();
_totpController.dispose();
super.dispose();
}
Future<void> _submitTransfer() async {
if (_confirming || _submitting) return;
final s = context.strings;
setState(() => _localError = null);
if (_needs2faSetup) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(this.context, s.transferTwoFaRequiredBody);
return;
}
if (_selectedWalletType == null ||
_emailController.text.trim().isEmpty ||
_amountController.text.isEmpty) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(this.context, s.transferFillFields);
return;
}
if (_requireWithdrawal2fa && _totpController.text.trim().length != 6) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(this.context, s.transferFillFields);
return;
}
final state = context.read<WalletBloc>().state;
final selectedType = state.walletTypes.firstWhere(
(t) => t.code == _selectedWalletType,
orElse: () => state.walletTypes.first,
);
final amountHuman = _amountController.text.trim();
final amountRaw = humanAmountToRaw(amountHuman, selectedType.decimals);
if (amountRaw == '0') {
setState(() => _localError = 'Enter a valid amount');
showErrorSnackBar(this.context, 'Enter a valid amount');
return;
}
setState(() => _confirming = true);
try {
// Force fresh balance + health before money confirm (never trust display cache).
final preflight = await fetchMoneyConfirmPreflight(
walletRepo: sl<WalletRepository>(),
healthRepo: sl<HealthRepository>(),
);
final profile = await sl<AuthRepository>().getProfile(force: true);
if (!mounted) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = preflight.health.requireWithdrawal2fa;
_securityFailed = false;
});
context.read<WalletBloc>().add(const WalletLoadRequested());
if (_requireWithdrawal2fa && _totpEnabled == false) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(this.context, s.transferTwoFaRequiredBody);
return;
}
final match = preflight.balances
.where((b) => b.walletType.code == _selectedWalletType)
.toList();
if (match.isEmpty) {
showErrorSnackBar(this.context, 'Wallet balance not loaded');
return;
}
final available = BigInt.tryParse(match.first.available) ?? BigInt.zero;
final need = BigInt.tryParse(amountRaw) ?? BigInt.zero;
if (need > available) {
showErrorSnackBar(this.context, 'Insufficient balance');
return;
}
final email = _emailController.text.trim().toLowerCase();
final confirmed = await showDialog<bool>(
context: this.context,
builder: (ctx) => AlertDialog(
title: const Text('Confirm transfer'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Amount: $amountHuman $_selectedWalletType'),
const SizedBox(height: 8),
Text('To: $email'),
const SizedBox(height: 16),
const Text(
'This will move balance to another user in this app. The recipient will see the balance immediately.',
style: TextStyle(fontSize: 13),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Confirm'),
),
],
),
);
if (confirmed == true && mounted) {
setState(() => _submitting = true);
final totp = _totpController.text.trim();
context.read<WalletBloc>().add(
WalletTransferRequested(
toEmail: email,
walletType: _selectedWalletType!,
amount: amountRaw,
totpCode: totp.isEmpty ? null : totp,
),
);
}
} catch (_) {
if (!mounted) return;
showErrorSnackBar(this.context, 'Could not refresh balance. Try again.');
} finally {
if (mounted) setState(() => _confirming = false);
}
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
key: const Key('transfer_screen'),
appBar: AppBar(title: Text(s.transfer)),
body: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.transferTxId != curr.transferTxId,
listener: (context, state) {
if (state.errorMessage != null && state.errorMessage!.isNotEmpty) {
setState(() {
_submitting = false;
_localError = state.errorMessage;
});
showErrorSnackBar(context, state.errorMessage!);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.transferTxId != null) {
setState(() => _submitting = false);
showSuccessSnackBar(context, s.transferCompleted);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
if (!state.isLoaded && state.balances.isEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: const [
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 48),
],
);
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: [
SectionError(
message: state.errorMessage ?? 'No wallet types',
onRetry: () => context
.read<WalletBloc>()
.add(const WalletLoadRequested()),
),
],
);
}
_selectedWalletType ??= types.first.code;
final selectedTypeList = types.where(
(t) => t.code == _selectedWalletType,
);
final selectedType = selectedTypeList.isEmpty
? types.first
: selectedTypeList.first;
final networkLabel = CoinDisplay.networkLabel(selectedType.code);
final busy = _submitting || _confirming;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_securityFailed) ...[
SectionError(
compact: true,
message: 'Could not verify 2FA requirements.',
onRetry: () => _loadSecurityContext(forceProfile: true),
),
const SizedBox(height: 16),
],
if (_needs2faSetup) ...[
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppColors.warning.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: AppColors.warning.withValues(alpha: 0.4),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.transferTwoFaRequiredTitle,
style: const TextStyle(fontWeight: FontWeight.w800),
),
const SizedBox(height: 6),
Text(
s.transferTwoFaRequiredBody,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 10),
OutlinedButton(
onPressed: () => context.push('/totp-setup'),
child: Text(s.enableTwoFa),
),
],
),
),
const SizedBox(height: 16),
],
if (_localError != null) ...[
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppColors.danger.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: AppColors.danger.withValues(alpha: 0.4),
),
),
child: Text(
_localError!,
style: const TextStyle(
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(height: 16),
],
const Text('Recipient email'),
const SizedBox(height: 8),
TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
enabled: !_needs2faSetup && !busy,
decoration: const InputDecoration(
labelText: 'Email address',
prefixIcon: Icon(Icons.email_outlined),
),
),
const SizedBox(height: 16),
const Text('Asset'),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
initialValue: _selectedWalletType,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(t.name),
),
)
.toList(),
onChanged: (_needs2faSetup || busy)
? null
: (v) => setState(() => _selectedWalletType = v),
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.info_outline,
size: 20,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Network: $networkLabel',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
const SizedBox(height: 16),
TextField(
controller: _amountController,
enabled: !_needs2faSetup && !busy,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
decoration: const InputDecoration(
labelText: 'Amount',
prefixIcon: Icon(Icons.attach_money),
),
),
if (balances.any(
(b) => b.walletType.code == _selectedWalletType,
)) ...[
const SizedBox(height: 8),
Text(
'Available: ${rawAmountToHuman(balances.firstWhere((b) => b.walletType.code == _selectedWalletType).available, selectedType.decimals)} $_selectedWalletType',
key: const Key('transfer_available'),
style: Theme.of(context).textTheme.bodySmall,
),
],
if (!_needs2faSetup) ...[
const SizedBox(height: 16),
Text(s.transferTotpHint),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: !busy,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpCode,
prefixIcon: const Icon(Icons.security),
),
),
],
const SizedBox(height: 24),
FilledButton(
key: const Key('transfer_submit'),
onPressed: busy ? null : _submitTransfer,
child: busy
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(s.transfer),
),
],
),
);
},
),
);
}
}