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

395 lines
12 KiB
Dart

/// Notifications presentation: security / system alerts with mark-read and pagination.
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import '../../../core/di/injection.dart';
import '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_colors.dart';
import '../../../data/models/notification_models.dart';
import '../../../domain/repositories/notification_repository.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';
class NotificationsScreen extends StatefulWidget {
const NotificationsScreen({super.key});
@override
State<NotificationsScreen> createState() => _NotificationsScreenState();
}
class _NotificationsScreenState extends State<NotificationsScreen> {
static const _pageSize = 20;
final _repo = sl<NotificationRepository>();
bool _loading = true;
bool _loadingMore = false;
bool _retrying = false;
String? _error;
List<SecurityNotificationModel> _items = [];
int _unreadCount = 0;
int _total = 0;
Future<void>? _listInFlight;
bool get _hasMore => _items.length < _total;
@override
void initState() {
super.initState();
final cached = _repo.peekLast();
if (cached != null) {
_items = cached.items;
_total = cached.total;
_unreadCount = cached.unreadCount;
_loading = false;
}
_load(reset: true);
}
Future<void> _load({required bool reset, bool force = false}) {
if (!reset) {
return _loadMore();
}
if (_listInFlight != null) return _listInFlight!;
final keep = _items.isNotEmpty && !force;
final future = () async {
if (!keep) {
setState(() {
_loading = true;
_error = null;
_retrying = force;
});
} else {
setState(() {
_error = null;
_retrying = force;
});
}
try {
final page = await _repo.list(
limit: _pageSize,
offset: 0,
force: force || !keep,
);
if (!mounted) return;
setState(() {
_items = page.items;
_total = page.total;
_unreadCount = page.unreadCount;
_loading = false;
_error = null;
_retrying = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_loading = false;
_retrying = false;
if (_items.isEmpty) {
_error = e is AppException
? e.message
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
}
});
}
}();
_listInFlight = future.whenComplete(() => _listInFlight = null);
return _listInFlight!;
}
Future<void> _loadMore() async {
if (_loadingMore || !_hasMore) return;
setState(() => _loadingMore = true);
try {
final page = await _repo.list(limit: _pageSize, offset: _items.length);
if (!mounted) return;
setState(() {
final existingIds = _items.map((e) => e.id).toSet();
_items = [
..._items,
...page.items.where((e) => !existingIds.contains(e.id)),
];
_total = page.total;
_unreadCount = page.unreadCount;
_loadingMore = false;
});
} catch (_) {
if (!mounted) return;
setState(() => _loadingMore = false);
}
}
Future<void> _markAll() async {
try {
await _repo.markAllRead();
await _load(reset: true, force: true);
} catch (_) {}
}
Future<void> _openItem(SecurityNotificationModel item) async {
if (item.isUnread) {
try {
await _repo.markRead(item.id);
if (mounted) {
setState(() {
final idx = _items.indexWhere((e) => e.id == item.id);
if (idx >= 0) {
final current = _items[idx];
_items[idx] = SecurityNotificationModel(
id: current.id,
eventType: current.eventType,
title: current.title,
body: current.body,
readAt: DateTime.now().toUtc().toIso8601String(),
createdAt: current.createdAt,
);
}
if (_unreadCount > 0) _unreadCount -= 1;
});
}
} catch (_) {}
}
if (!mounted) return;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useRootNavigator: true,
showDragHandle: true,
backgroundColor: Theme.of(context).colorScheme.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (ctx) {
final isDark = Theme.of(ctx).brightness == Brightness.dark;
final muted =
isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.title,
style: const TextStyle(
fontWeight: FontWeight.w800,
fontSize: 18,
),
),
const SizedBox(height: 6),
Text(
_formatDate(item.createdAt),
style: Theme.of(ctx).textTheme.bodySmall?.copyWith(
color: muted,
),
),
const SizedBox(height: 14),
Text(item.body, style: Theme.of(ctx).textTheme.bodyMedium),
],
),
),
);
},
);
}
String _formatDate(String iso) {
final dt = DateTime.tryParse(iso)?.toLocal();
if (dt == null) return iso;
return DateFormat('dd/MM/yyyy HH:mm').format(dt);
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final bottomInset = MediaQuery.paddingOf(context).bottom;
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
final secondary =
isDark ? AppColors.textSecondary : const Color(0xFF475569);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('notifications_screen'),
body: Column(
children: [
TlotoGradientAppBar(
title: s.notificationsTitle,
showBack: true,
actions: [
if (_unreadCount > 0)
TextButton(
onPressed: _markAll,
child: Text(
s.markAllRead,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
),
),
),
],
),
Expanded(
child: RefreshIndicator(
onRefresh: () => _load(reset: true, force: true),
child: _buildBody(s, muted, secondary, bottomInset),
),
),
],
),
),
);
}
Widget _buildBody(
AppStrings s,
Color muted,
Color secondary,
double bottomInset,
) {
const physics = AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
);
final listPadding = EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset);
if (_loading && _items.isEmpty) {
return ListView(
physics: physics,
padding: listPadding,
children: const [
PredSkeletonCard(height: 72),
SizedBox(height: 8),
PredSkeletonCard(height: 72),
SizedBox(height: 8),
PredSkeletonCard(height: 72),
SizedBox(height: 8),
PredSkeletonCard(height: 72),
],
);
}
if (_error != null && _items.isEmpty) {
return ListView(
physics: physics,
padding: listPadding,
children: [
SectionError(
message: _error!,
retrying: _retrying,
onRetry: () => _load(reset: true, force: true),
),
],
);
}
if (_items.isEmpty) {
return ListView(
physics: physics,
padding: EdgeInsets.fromLTRB(40, 40, 40, 40 + bottomInset),
children: [
Icon(Icons.notifications_none_rounded, size: 48, color: muted),
const SizedBox(height: 12),
Text(
s.noNotifications,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: secondary,
),
),
],
);
}
final remaining = (_total - _items.length).clamp(0, _pageSize);
return ListView.separated(
physics: physics,
padding: listPadding,
itemCount: _items.length + (_hasMore ? 1 : 0),
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) {
if (index >= _items.length) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Center(
child: _loadingMore
? const SizedBox(
width: 28,
height: 28,
child: CircularProgressIndicator(strokeWidth: 2.5),
)
: TextButton(
key: const Key('notifications_load_more'),
onPressed: () => _load(reset: false),
child: Text(s.loadMoreRemaining(remaining)),
),
),
);
}
final item = _items[index];
return PredCard(
onTap: () => _openItem(item),
padding: const EdgeInsets.all(14),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 10,
height: 10,
margin: const EdgeInsets.only(top: 5),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: item.isUnread ? AppColors.primary : AppColors.border,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.title,
style: TextStyle(
fontWeight:
item.isUnread ? FontWeight.w800 : FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
item.body,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: secondary),
),
const SizedBox(height: 6),
Text(
_formatDate(item.createdAt),
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(color: muted),
),
],
),
),
],
),
);
},
);
}
}