games_app/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart
2026-07-25 22:48:54 +02:00

364 lines
13 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 '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/repositories.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../bloc/wallet_bloc.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;
String? _localError;
bool get _needs2faSetup => _requireWithdrawal2fa && _totpEnabled == false;
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested());
_loadSecurityContext();
}
Future<void> _loadSecurityContext() async {
try {
final profile = await sl<AuthRepository>().getProfile();
final health = await sl<HealthRepository>().getHealth();
if (!mounted) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = health.requireWithdrawal2fa;
});
} catch (_) {
if (!mounted) return;
setState(() {
_totpEnabled ??= false;
});
}
}
@override
void dispose() {
_emailController.dispose();
_amountController.dispose();
_totpController.dispose();
super.dispose();
}
void _submitTransfer(BuildContext context) {
final s = context.strings;
setState(() => _localError = null);
if (_needs2faSetup) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
return;
}
if (_selectedWalletType == null ||
_emailController.text.trim().isEmpty ||
_amountController.text.isEmpty) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
return;
}
if (_requireWithdrawal2fa && _totpController.text.trim().length != 6) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(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(context, 'Enter a valid amount');
return;
}
final email = _emailController.text.trim().toLowerCase();
showDialog<bool>(
context: 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'),
),
],
),
).then((confirmed) {
if (confirmed == true && context.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,
),
);
}
});
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
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 const Center(child: CircularProgressIndicator());
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
return const Center(child: Text('No wallet types'));
}
_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);
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
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,
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
? 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,
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',
style: Theme.of(context).textTheme.bodySmall,
),
],
if (!_needs2faSetup) ...[
const SizedBox(height: 16),
Text(s.transferTotpHint),
const SizedBox(height: 8),
TextField(
controller: _totpController,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpCode,
prefixIcon: const Icon(Icons.security),
),
),
],
const SizedBox(height: 24),
FilledButton(
onPressed: _submitting ? null : () => _submitTransfer(context),
child: _submitting
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(s.transfer),
),
],
),
);
},
),
);
}
}