games_app/prediqo_mobile/lib/features/admin/presentation/settings_screen.dart
2026-10-25 20:49:23 +02:00

472 lines
16 KiB
Dart

/// Admin presentation: system settings (password policy and token expiry).
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/theme/app_theme.dart';
import '../../../data/repositories/admin_repository_impl.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/section_error.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../../auth/bloc/auth_bloc.dart';
/// Admin-only screen to view and update password policy and JWT expiry settings.
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key, required this.adminRepo});
final AdminRepositoryImpl adminRepo;
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
/// Loads settings on init and persists changes via [AdminRepositoryImpl].
class _SettingsScreenState extends State<SettingsScreen> {
SystemSettings? _settings;
bool _loading = true;
bool _retrying = false;
String? _error;
bool _saving = false;
final _minLengthController = TextEditingController();
final _accessExpiryController = TextEditingController();
final _refreshExpiryController = TextEditingController();
@override
void initState() {
super.initState();
final cached = widget.adminRepo.peekLastSettings();
if (cached != null) {
_settings = cached;
_minLengthController.text = cached.passwordMinLength.toString();
_accessExpiryController.text = cached.accessTokenExpiry;
_refreshExpiryController.text = cached.refreshTokenExpiry;
_loading = false;
}
_load();
}
@override
void dispose() {
_minLengthController.dispose();
_accessExpiryController.dispose();
_refreshExpiryController.dispose();
super.dispose();
}
void _applySettings(SystemSettings s) {
_settings = s;
_minLengthController.text = s.passwordMinLength.toString();
_accessExpiryController.text = s.accessTokenExpiry;
_refreshExpiryController.text = s.refreshTokenExpiry;
}
/// Fetches current system settings and populates form controllers.
Future<void> _load({bool force = false}) async {
final keepForm = _settings != null;
setState(() {
_loading = !keepForm;
_retrying = force && !keepForm;
if (!force) _error = null;
});
try {
final s = await widget.adminRepo.getSettings(force: force || !keepForm);
if (mounted) {
setState(() {
_applySettings(s);
_loading = false;
_retrying = false;
_error = null;
});
}
} catch (e) {
if (mounted) {
setState(() {
_loading = false;
_retrying = false;
if (_settings == null) {
_error = e.toString().replaceFirst('Exception: ', '');
}
});
}
}
}
/// Validates form values and submits updated settings to the API.
Future<void> _save() async {
final s = context.strings;
final minLen = int.tryParse(_minLengthController.text.trim());
if (minLen == null || minLen < 1 || minLen > 128) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(s.passwordMinLengthInvalid)),
);
return;
}
final accessExpiry = _accessExpiryController.text.trim();
final refreshExpiry = _refreshExpiryController.text.trim();
if (accessExpiry.isEmpty || refreshExpiry.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(s.tokenExpiryRequired)),
);
return;
}
setState(() => _saving = true);
try {
final updated = SystemSettings(
passwordMinLength: minLen,
passwordRequireUppercase: _settings!.passwordRequireUppercase,
passwordRequireLowercase: _settings!.passwordRequireLowercase,
passwordRequireNumber: _settings!.passwordRequireNumber,
passwordRequireSpecial: _settings!.passwordRequireSpecial,
accessTokenExpiry: accessExpiry,
refreshTokenExpiry: refreshExpiry,
);
final result = await widget.adminRepo.updateSettings(updated);
if (mounted) {
setState(() {
_settings = result;
_saving = false;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(s.settingsSaved)),
);
}
} catch (e) {
if (mounted) {
setState(() => _saving = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toString().replaceFirst('Exception: ', ''))),
);
}
}
}
Widget _settingsBody(BuildContext context) {
final s = context.strings;
final bottomInset = MediaQuery.paddingOf(context).bottom;
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
if (_error != null && _settings == null) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
children: [
SectionError(
message: _error!,
retrying: _retrying,
onRetry: () => _load(force: true),
),
],
);
}
if (_loading && _settings == null) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
children: const [
PredSkeletonCard(height: 120),
SizedBox(height: 16),
PredSkeletonCard(height: 120),
SizedBox(height: 24),
PredSkeletonCard(height: 48),
],
);
}
final primary = Theme.of(context).colorScheme.primary;
return ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
20,
12,
20,
24 + bottomInset + keyboardInset,
),
children: [
PredCard(
padding: EdgeInsets.zero,
child: Theme(
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
initiallyExpanded: false,
tilePadding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 2,
),
childrenPadding: const EdgeInsets.fromLTRB(14, 8, 14, 16),
leading: Icon(Icons.password_rounded, color: primary),
title: Text(
s.passwordPolicy,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
),
subtitle: Text(
s.passwordPolicySubtitle,
style: Theme.of(context).textTheme.bodySmall,
),
children: [
_LabeledField(
label: s.passwordMinLength,
helperText: s.passwordMinLengthHelper,
child: TextField(
controller: _minLengthController,
style: Theme.of(context).textTheme.bodyLarge,
decoration: const InputDecoration(),
keyboardType: TextInputType.number,
),
),
const SizedBox(height: 8),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: Text(s.requireUppercase),
value: _settings!.passwordRequireUppercase,
onChanged: (v) => setState(() {
_settings = SystemSettings(
passwordMinLength: _settings!.passwordMinLength,
passwordRequireUppercase: v ?? true,
passwordRequireLowercase:
_settings!.passwordRequireLowercase,
passwordRequireNumber: _settings!.passwordRequireNumber,
passwordRequireSpecial: _settings!.passwordRequireSpecial,
accessTokenExpiry: _settings!.accessTokenExpiry,
refreshTokenExpiry: _settings!.refreshTokenExpiry,
);
}),
),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: Text(s.requireLowercase),
value: _settings!.passwordRequireLowercase,
onChanged: (v) => setState(() {
_settings = SystemSettings(
passwordMinLength: _settings!.passwordMinLength,
passwordRequireUppercase:
_settings!.passwordRequireUppercase,
passwordRequireLowercase: v ?? true,
passwordRequireNumber: _settings!.passwordRequireNumber,
passwordRequireSpecial: _settings!.passwordRequireSpecial,
accessTokenExpiry: _settings!.accessTokenExpiry,
refreshTokenExpiry: _settings!.refreshTokenExpiry,
);
}),
),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: Text(s.requireNumber),
value: _settings!.passwordRequireNumber,
onChanged: (v) => setState(() {
_settings = SystemSettings(
passwordMinLength: _settings!.passwordMinLength,
passwordRequireUppercase:
_settings!.passwordRequireUppercase,
passwordRequireLowercase:
_settings!.passwordRequireLowercase,
passwordRequireNumber: v ?? true,
passwordRequireSpecial: _settings!.passwordRequireSpecial,
accessTokenExpiry: _settings!.accessTokenExpiry,
refreshTokenExpiry: _settings!.refreshTokenExpiry,
);
}),
),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: Text(s.requireSpecial),
value: _settings!.passwordRequireSpecial,
onChanged: (v) => setState(() {
_settings = SystemSettings(
passwordMinLength: _settings!.passwordMinLength,
passwordRequireUppercase:
_settings!.passwordRequireUppercase,
passwordRequireLowercase:
_settings!.passwordRequireLowercase,
passwordRequireNumber: _settings!.passwordRequireNumber,
passwordRequireSpecial: v ?? true,
accessTokenExpiry: _settings!.accessTokenExpiry,
refreshTokenExpiry: _settings!.refreshTokenExpiry,
);
}),
),
],
),
),
),
const SizedBox(height: 10),
PredCard(
padding: EdgeInsets.zero,
child: Theme(
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
initiallyExpanded: false,
tilePadding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 2,
),
childrenPadding: const EdgeInsets.fromLTRB(14, 8, 14, 16),
leading: Icon(Icons.timer_outlined, color: primary),
title: Text(
s.tokenExpiration,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
),
subtitle: Text(
s.tokenExpirationSubtitle,
style: Theme.of(context).textTheme.bodySmall,
),
children: [
Text(
s.tokenExpiryHint,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
_LabeledField(
label: s.accessTokenExpiry,
helperText: s.tokenExpiryExampleShort,
child: TextField(
controller: _accessExpiryController,
style: Theme.of(context).textTheme.bodyLarge,
decoration: const InputDecoration(),
),
),
const SizedBox(height: 12),
_LabeledField(
label: s.refreshTokenExpiry,
helperText: s.tokenExpiryExampleLong,
child: TextField(
controller: _refreshExpiryController,
style: Theme.of(context).textTheme.bodyLarge,
decoration: const InputDecoration(),
),
),
],
),
),
),
const SizedBox(height: 24),
FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(s.saveSettings),
),
],
);
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return BlocBuilder<AuthBloc, AuthState>(
buildWhen: (prev, next) => prev.isAdmin != next.isAdmin,
builder: (context, authState) {
if (!authState.isAdmin) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
body: Column(
children: [
TlotoGradientAppBar(
title: s.settings,
showBack: true,
),
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
s.accessDeniedAdmin,
textAlign: TextAlign.center,
style: TextStyle(color: AppColors.textMuted),
),
),
),
),
],
),
),
);
}
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('admin_settings_screen'),
body: Column(
children: [
TlotoGradientAppBar(
title: s.settings,
showBack: true,
),
Expanded(
child: RefreshIndicator(
onRefresh: () => _load(force: true),
child: _settingsBody(context),
),
),
],
),
),
);
},
);
}
}
/// Label + field outside [InputDecoration] so ExpansionTile does not clip it.
class _LabeledField extends StatelessWidget {
const _LabeledField({
required this.label,
required this.child,
this.helperText,
});
final String label;
final Widget child;
final String? helperText;
@override
Widget build(BuildContext context) {
final primary = Theme.of(context).colorScheme.primary;
final muted = Theme.of(context).brightness == Brightness.dark
? AppColors.textMuted
: const Color(0xFF64748B);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
label,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: primary,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
child,
if (helperText != null) ...[
const SizedBox(height: 6),
Text(
helperText!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: muted),
),
],
],
);
}
}