games_app/prediqo_mobile/lib/features/notifications/presentation/notifications_screen.dart
2026-07-27 09:29:50 +02:00

290 lines
11 KiB
Dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../core/di/injection.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_text_field.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;
String? _error;
List<SecurityNotificationModel> _items = [];
int _unreadCount = 0;
int _total = 0;
bool get _hasMore => _items.length < _total;
@override
void initState() {
super.initState();
_load(reset: true);
}
Future<void> _load({required bool reset}) async {
if (reset) {
setState(() {
_loading = true;
_error = null;
});
} else {
if (_loadingMore || !_hasMore) return;
setState(() => _loadingMore = true);
}
try {
final offset = reset ? 0 : _items.length;
final page = await _repo.list(limit: _pageSize, offset: offset);
if (!mounted) return;
setState(() {
if (reset) {
_items = page.items;
} else {
final existingIds = _items.map((e) => e.id).toSet();
_items = [
..._items,
...page.items.where((e) => !existingIds.contains(e.id)),
];
}
_total = page.total;
_unreadCount = page.unreadCount;
_loading = false;
_loadingMore = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
if (reset) {
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
}
_loading = false;
_loadingMore = false;
});
}
}
Future<void> _markAll() async {
try {
await _repo.markAllRead();
await _load(reset: 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,
backgroundColor: AppColors.surfaceCard,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (ctx) {
return Padding(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + MediaQuery.paddingOf(ctx).bottom,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.border,
borderRadius: BorderRadius.circular(999),
),
),
),
const SizedBox(height: 16),
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: AppColors.textMuted,
),
),
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;
return Scaffold(
appBar: AppBar(
title: Text(s.notificationsTitle),
actions: [
if (_unreadCount > 0)
TextButton(
onPressed: _markAll,
child: Text(s.markAllRead),
),
],
),
body: _loading
? PredLoadingView(message: s.loading)
: _error != null
? PredErrorView(message: _error!, onRetry: () => _load(reset: true))
: RefreshIndicator(
onRefresh: () => _load(reset: true),
child: _items.isEmpty
? ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(40),
children: [
const Icon(
Icons.notifications_none_rounded,
size: 48,
color: AppColors.textMuted,
),
const SizedBox(height: 12),
Text(
s.noNotifications,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: AppColors.textSecondary,
),
),
],
)
: ListView.separated(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
itemCount: _items.length + (_hasMore ? 1 : 0),
separatorBuilder: (_, __) => const SizedBox(height: 10),
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),
)
: OutlinedButton(
onPressed: () => _load(reset: false),
child: Text(s.loadMore),
),
),
);
}
final item = _items[index];
return PredCard(
onTap: () => _openItem(item),
padding: const EdgeInsets.all(16),
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: AppColors.textSecondary),
),
const SizedBox(height: 6),
Text(
_formatDate(item.createdAt),
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(color: AppColors.textMuted),
),
],
),
),
],
),
);
},
),
),
);
}
}