import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../services/app_settings.dart'; import '../services/target_repository.dart'; import '../theme/app_theme.dart'; import '../widgets/section.dart'; import 'target_view.dart'; /// One training or tournament: its stats, its targets, and edit/delete actions. class SessionScreen extends StatefulWidget { final Session session; const SessionScreen({super.key, required this.session}); @override State createState() => _SessionScreenState(); } class _SessionScreenState extends State { late Session _session = widget.session; Future _reload() async { final sessions = await TargetRepository.loadSessions(); final updated = sessions.where((s) => s.name == _session.name); if (!mounted) return; if (updated.isEmpty) { Navigator.pop(context); // session no longer exists } else { setState(() => _session = updated.first); } } void _openTargets(List targets) { Navigator.push( context, MaterialPageRoute( builder: (_) => TargetViewScreen( jsonFiles: [for (final t in targets) t.file], refreshFolders: _reload, ), ), ); } Future _edit() async { final result = await showEditSessionDialog(context, _session); if (result == null) return; final ok = await TargetRepository.updateSession(_session, name: result.name, isTournament: result.isTournament); if (!mounted) return; if (!ok) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(AppSettings.instance.t('A folder with this name already exists'))), ); return; } _session = Session(name: result.name, isTournament: result.isTournament, date: _session.date, targets: _session.targets); _reload(); } Future _delete() async { final s = AppSettings.instance; final message = '${s.t('Are you sure you want to delete the folder')} "${_session.name}" ${s.t('and all of its contents?')}'; if (await confirmDelete(context, message) != true) return; await TargetRepository.deleteSession(_session); if (mounted) Navigator.pop(context); } Future _deleteTarget(TargetRecord target) async { if (await confirmDelete(context, AppSettings.instance.t('Are you sure you want to delete this file?')) != true) return; await TargetRepository.deleteTarget(target); _reload(); } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: AppSettings.instance, builder: (context, _) { final s = AppSettings.instance; final t = s.t; final surf = Surfaces.current; final session = _session; final stats = ShooterStats.of([session]); return Scaffold( backgroundColor: s.backgroundColor, appBar: AppBar( title: Text(session.name, style: const TextStyle(color: Colors.white)), backgroundColor: AppTheme.bar, iconTheme: const IconThemeData(color: Colors.white), scrolledUnderElevation: 0, actions: [ IconButton(icon: const Icon(Icons.edit), tooltip: t('Edit'), onPressed: _edit), IconButton(icon: const Icon(Icons.delete, color: Colors.red), tooltip: t('Delete'), onPressed: _delete), ], ), body: ListView( // Keep the last row clear of the system gesture bar (edge-to-edge) padding: EdgeInsets.fromLTRB(16, 4, 16, 24 + MediaQuery.paddingOf(context).bottom), children: [ SectionHeader( '${session.isTournament ? t('Tournament') : t('Training')} · ${DateFormat('d. M. yyyy').format(session.date)}', ), StatGrid(tiles: [ StatTile(label: t('Total'), value: '${session.totalScore}', caption: targetCount(session.targets.length)), StatTile( label: t('Average per shot'), value: stats.averagePerShot?.toStringAsFixed(2) ?? '–', caption: shotCount(stats.shots), ), ]), SectionHeader(t('Targets')), if (session.targets.isEmpty) Padding( padding: const EdgeInsets.all(16), child: Text(t('No targets in this folder'), style: TextStyle(color: surf.textSecondary)), ) else GroupCard(children: [ for (int i = 0; i < session.targets.length; i++) SettingsTile( title: '${t('Target')} ${i + 1}', subtitle: '${DateFormat('HH:mm').format(session.targets[i].shotAt)} · ${shotCount(session.targets[i].shots)}', onTap: () => _openTargets([session.targets[i]]), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ Text( '${session.targets[i].score}', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: surf.textPrimary), ), IconButton( icon: const Icon(Icons.delete, color: Colors.red, size: 20), onPressed: () => _deleteTarget(session.targets[i]), ), ], ), ), ]), ], ), ); }, ); } } /// "1 target" / "5 targets", with Slovenian dual and plural forms. String targetCount(int n) { final s = AppSettings.instance; if (s.language != 'Slovenian') return n == 1 ? '1 target' : '$n targets'; final mod = n % 100; final word = mod == 1 ? 'tarča' : mod == 2 ? 'tarči' : (mod == 3 || mod == 4) ? 'tarče' : 'tarč'; return '$n $word'; } /// "1 shot" / "5 shots", with Slovenian dual and plural forms. String shotCount(int n) { final s = AppSettings.instance; if (s.language != 'Slovenian') return n == 1 ? '1 shot' : '$n shots'; final mod = n % 100; final word = mod == 1 ? 'strel' : mod == 2 ? 'strela' : (mod == 3 || mod == 4) ? 'streli' : 'strelov'; return '$n $word'; } Future confirmDelete(BuildContext context, String message) { final s = AppSettings.instance; return showDialog( context: context, builder: (dialog) => AlertDialog( title: Text(s.t('Confirm Deletion')), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.pop(dialog, false), child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), ), FilledButton( style: FilledButton.styleFrom(backgroundColor: Colors.red[700]), onPressed: () => Navigator.pop(dialog, true), child: Text(s.t('Yes, delete')), ), ], ), ); } class SessionEdit { final String name; final bool isTournament; const SessionEdit(this.name, this.isTournament); } /// Rename a session and choose training/tournament. Future showEditSessionDialog(BuildContext context, Session session) { final s = AppSettings.instance; final controller = TextEditingController(text: session.name); var isTournament = session.isTournament; return showDialog( context: context, builder: (dialog) => StatefulBuilder( builder: (context, setDialogState) => AlertDialog( title: Text(s.t('Folder Settings')), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: controller, style: const TextStyle(color: Colors.white), cursorColor: s.bulletColor, decoration: InputDecoration( filled: true, fillColor: Colors.white10, border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: s.bulletColor), ), ), ), const SizedBox(height: 8), SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(s.t('Tournament'), style: const TextStyle(color: Colors.white)), secondary: Icon(Icons.emoji_events, color: isTournament ? s.bulletColor : Colors.white54), value: isTournament, activeTrackColor: s.bulletColor, onChanged: (v) => setDialogState(() => isTournament = v), ), ], ), actions: [ TextButton( onPressed: () => Navigator.pop(dialog), child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), ), FilledButton( style: FilledButton.styleFrom(backgroundColor: s.bulletColor), onPressed: () { final name = controller.text.trim(); if (name.isEmpty || name.contains('/')) return; Navigator.pop(dialog, SessionEdit(name, isTournament)); }, child: Text(s.t('Save')), ), ], ), ), ); }