Files
SDKmuta/lib/screens/calendar_screen.dart
T
2026-10-26 20:48:16 +01:00

890 lines
30 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/contact.dart';
import '../services/app_settings.dart';
import '../theme/app_theme.dart';
import '../widgets/bar_tabs.dart';
import '../services/google_calendar_service.dart';
import '../services/notification_service.dart';
import '../utils/translations.dart';
import '../utils/target_colors.dart';
enum EventType {
regular,
competition,
sestanek,
}
class CalendarScreen extends StatefulWidget {
const CalendarScreen({super.key});
@override
State<CalendarScreen> createState() => _CalendarScreenState();
}
class _CalendarScreenState extends State<CalendarScreen> {
final GoogleCalendarService _calendarService = GoogleCalendarService();
bool _isLoading = false;
List<CalendarEvent> _events = [];
String? _errorMessage;
String _bulletColor = 'Blue';
String _selectedLanguage = 'English';
bool _showContacts = false;
late Color _backgroundColor;
List<Contact> get _contacts => AppSettings.instance.clubContacts;
@override
void initState() {
super.initState();
initializeDateFormatting('sl_SI', null);
_backgroundColor = AppSettings.instance.backgroundColor;
_loadBulletColor();
_loadLanguage();
_loadSelectedTargetColor();
_loadEvents();
}
String _t(String key) => AppTranslations.translate(key, _selectedLanguage);
Future<void> _loadLanguage() async {
final prefs = await SharedPreferences.getInstance();
setState(
() => _selectedLanguage = prefs.getString('language') ?? 'English');
}
Future<void> _loadSelectedTargetColor() async {
final prefs = await SharedPreferences.getInstance();
final selectedTarget =
prefs.getString('selectedTarget') ?? 'assets/target.png';
setState(() =>
_backgroundColor = TargetColors.getBackgroundColor(selectedTarget));
}
@override
void dispose() {
_calendarService.dispose();
super.dispose();
}
Future<void> _loadBulletColor() async {
final prefs = await SharedPreferences.getInstance();
setState(() => _bulletColor = prefs.getString('bulletColor') ?? 'Blue');
}
Color _getAccentColor() {
switch (_bulletColor.toLowerCase()) {
case 'blue':
return Colors.blue;
case 'green':
return Colors.green;
case 'yellow':
return Colors.yellow;
case 'purple':
return Colors.purple;
case 'cyan':
return Colors.cyan;
case 'teal':
return Colors.teal;
case 'indigo':
return Colors.indigo;
case 'pink':
return Colors.pink;
case 'lime':
return Colors.lime;
case 'mint':
return Colors.greenAccent;
case 'orange':
return Colors.orange;
case 'violet':
return Colors.deepPurpleAccent;
case 'amber':
return Colors.amber;
case 'brown':
return Colors.brown;
case 'grey':
return Colors.grey;
default:
return Colors.blue;
}
}
bool _isValidEvent(CalendarEvent event) {
if (event.summary == null || event.summary!.trim().isEmpty) return false;
return event.summary!.trim().length >= 2;
}
EventType? _getEventType(CalendarEvent event) {
if (event.summary == null) return null;
final summary = event.summary!.toLowerCase();
if (summary.contains('liga') ||
summary.contains('tekmovanje') ||
summary.contains('tekma')) {
return EventType.competition;
} else if (summary.contains('sestanek')) {
return EventType.sestanek;
} else if (summary.contains('dežurstvo')) {
return EventType.regular;
}
return null;
}
Future<void> _loadEvents() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final events = await _calendarService.getEvents(
startDate: DateTime.now(),
endDate: DateTime.now().add(const Duration(days: 365)),
);
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final filteredEvents = events.where((event) {
if (!_isValidEvent(event)) return false;
if (_getEventType(event) == null) return false;
if (event.startTime != null) {
final eventDate = DateTime(event.startTime!.year,
event.startTime!.month, event.startTime!.day);
return eventDate.isAtSameMomentAs(today) || eventDate.isAfter(today);
}
return false;
}).toList();
filteredEvents.sort((a, b) {
if (a.startTime == null) return 1;
if (b.startTime == null) return -1;
return a.startTime!.compareTo(b.startTime!);
});
if (mounted) {
setState(() => _events = filteredEvents);
}
NotificationService().scheduleEventNotifications(filteredEvents);
} catch (e) {
if (mounted) {
setState(() => _errorMessage = 'Error loading events: $e');
}
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
}
Future<void> _makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber);
try {
await launchUrl(launchUri);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${_t('Could not launch phone call: ')}$e')),
);
}
}
}
String _capitalize(String text) {
return text.split(' ').map((word) {
if (word.isEmpty) return word;
return word[0].toUpperCase() + word.substring(1).toLowerCase();
}).join(' ');
}
void _copyToClipboard(String text, String label) {
Clipboard.setData(ClipboardData(text: text));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('$label ${_t('copied to clipboard')}'),
duration: const Duration(seconds: 2),
),
);
}
void _showContactPopup(BuildContext context, Contact contact) {
final accentColor = _getAccentColor();
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) {
// SafeArea keeps the buttons above Android's gesture bar (edge-to-edge)
return SafeArea(
child: RepaintBoundary(
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: accentColor,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
contact.firstName[0].toUpperCase(),
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold),
),
),
),
const SizedBox(width: 16),
Expanded(
child: Text(
_capitalize(contact.fullName),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
],
),
),
_buildContactDetailRow(
accentColor, Icons.phone, _t('Phone'), contact.phone, () {
_copyToClipboard(contact.phone, 'Phone number');
Navigator.pop(context);
}),
const SizedBox(height: 12),
_buildContactDetailRow(accentColor, Icons.email, _t('Email'),
contact.email.toLowerCase(), () {
_copyToClipboard(contact.email, 'Email address');
Navigator.pop(context);
}),
],
),
),
),
);
},
);
}
Widget _buildContactDetailRow(Color accentColor, IconData icon, String label,
String value, VoidCallback onCopy) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
decoration: BoxDecoration(
color: Colors.grey[850], borderRadius: BorderRadius.circular(10)),
child: Row(
children: [
Icon(icon, color: accentColor, size: 20),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
style: const TextStyle(color: Colors.grey, fontSize: 11)),
Text(value,
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600),
maxLines: 1,
overflow: TextOverflow.ellipsis),
],
),
),
Container(
decoration: BoxDecoration(
color: accentColor, borderRadius: BorderRadius.circular(8)),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onCopy,
borderRadius: BorderRadius.circular(8),
child: const Padding(
padding: EdgeInsets.all(8),
child:
Icon(Icons.content_copy, color: Colors.white, size: 18),
),
),
),
),
],
),
);
}
Widget _buildContactsList() {
final accentColor = _getAccentColor();
return ListView.builder(
itemCount: _contacts.length,
padding: const EdgeInsets.all(8),
itemBuilder: (context, index) {
final contact = _contacts[index];
return GestureDetector(
// Card opens the info sheet (copy number/e-mail); the call strip on the right calls
onTap: () => _showContactPopup(context, contact),
child: Container(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
decoration: BoxDecoration(
color: Surfaces.current.card,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.15),
blurRadius: 6,
offset: const Offset(0, 2)),
],
),
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.6),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12)),
),
child: Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(2)),
),
const SizedBox(width: 12),
Expanded(
child: Text(
_capitalize(contact.fullName),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 14, vertical: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(Icons.phone, size: 14, color: accentColor),
const SizedBox(width: 6),
Text(contact.phone,
style: TextStyle(
fontSize: 12,
color: Surfaces.current.textPrimary,
fontWeight: FontWeight.w500)),
]),
const SizedBox(height: 4),
Row(children: [
Icon(Icons.email, size: 14, color: accentColor),
const SizedBox(width: 6),
Expanded(
child: Text(contact.email.toLowerCase(),
style: TextStyle(
fontSize: 12,
color: Surfaces.current.textPrimary,
fontWeight: FontWeight.w500),
overflow: TextOverflow.ellipsis),
),
]),
],
),
),
],
),
Positioned(
right: 0,
top: 0,
bottom: 0,
child: Container(
width: 80,
decoration: BoxDecoration(
color: accentColor,
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10),
bottomRight: Radius.circular(10)),
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () => _makePhoneCall(contact.phone),
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10),
bottomRight: Radius.circular(10)),
child: const Center(
child: Icon(Icons.call,
color: Colors.white, size: 22)),
),
),
),
),
],
),
),
);
},
);
}
Color _eventColor(EventType type, Color accentColor) {
switch (type) {
case EventType.competition:
return Colors.orange;
case EventType.sestanek:
return const Color(0xFFE53935);
case EventType.regular:
return accentColor;
}
}
IconData _eventIcon(EventType type) {
switch (type) {
case EventType.competition:
return Icons.emoji_events;
case EventType.sestanek:
return Icons.people;
case EventType.regular:
return Icons.calendar_today;
}
}
String _eventBadgeLabel(EventType type) {
switch (type) {
case EventType.competition:
return _t('COMPETITION');
case EventType.sestanek:
return _t('MEETING');
case EventType.regular:
return _t('DUTY');
}
}
String _timeText(CalendarEvent event) {
final startTime = event.startTime;
if (event.isAllDay || startTime == null || event.endTime == null)
return _t('All day');
return '${DateFormat('HH:mm').format(startTime.toLocal())} – ${DateFormat('HH:mm').format(event.endTime!.toLocal())}';
}
// When [date] is given, the type stripe widens into a date block (upcoming list).
Widget _buildEventCard(CalendarEvent event, Color accentColor,
{bool highlight = false, DateTime? date, int daysFromToday = 0}) {
final eventType = _getEventType(event);
if (eventType == null) return const SizedBox();
final color = _eventColor(eventType, accentColor);
final hasLocation = event.location != null && event.location!.isNotEmpty;
final surf = Surfaces.current;
return RepaintBoundary(
child: Container(
decoration: BoxDecoration(
color: surf.card,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.15),
blurRadius: 6,
offset: const Offset(0, 2)),
],
),
clipBehavior: Clip.antiAlias,
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Type color stripe, or date block for upcoming events
date != null
? _buildDateBlock(date, daysFromToday, color)
: Container(width: 5, color: color),
Expanded(
child: Padding(
padding: EdgeInsets.fromLTRB(
12, highlight ? 12 : 10, 12, highlight ? 12 : 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
_buildTypeChip(_eventIcon(eventType),
_eventBadgeLabel(eventType), color),
const Spacer(),
Icon(Icons.access_time,
size: 13, color: surf.textSecondary),
const SizedBox(width: 4),
Text(
_timeText(event),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: surf.textSecondary),
),
],
),
const SizedBox(height: 8),
Text(
event.summary ?? _t('Untitled Event'),
style: TextStyle(
fontSize: highlight ? 16 : 14,
fontWeight: FontWeight.w700,
color: surf.textPrimary,
),
),
if (hasLocation) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.location_on,
size: 13, color: surf.textSecondary),
const SizedBox(width: 4),
Expanded(
child: Text(
event.location!,
style: TextStyle(
fontSize: 12, color: surf.textSecondary),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
],
],
),
),
),
],
),
),
),
);
}
Widget _buildTypeChip(IconData icon, String label, Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 11, color: color),
const SizedBox(width: 4),
Text(label,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: color,
letterSpacing: 0.6)),
],
),
);
}
Widget _buildSectionHeader(String label, Color dotColor, Color textColor,
{String? trailing, Color? trailingColor}) {
return Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle),
),
const SizedBox(width: 8),
Text(label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: textColor,
letterSpacing: 1.4)),
if (trailing != null) ...[
const SizedBox(width: 8),
Expanded(
child: Text(
'· $trailing',
style: TextStyle(fontSize: 12, color: trailingColor ?? textColor),
overflow: TextOverflow.ellipsis,
),
),
],
],
);
}
Widget _buildDateBlock(DateTime date, int daysFromToday, Color color) {
final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US';
final relative = daysFromToday == 1
? _t('Tomorrow')
: _t('in {n} days').replaceAll('{n}', '$daysFromToday');
return Container(
width: 56,
color: color,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 2),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
DateFormat('EEE', locale).format(date).toUpperCase(),
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w700,
color: Colors.white.withValues(alpha: 0.9),
letterSpacing: 0.8),
),
Text(
DateFormat('d').format(date),
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.white,
height: 1.15),
),
Text(
relative,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 9,
fontWeight:
daysFromToday == 1 ? FontWeight.bold : FontWeight.w500,
color: Colors.white.withValues(alpha: 0.9),
),
),
],
),
);
}
bool _isLightBackground() {
return _backgroundColor.computeLuminance() > 0.4;
}
Widget _buildCalendarView(Color accentColor) {
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US';
final isLight = _isLightBackground();
final textPrimary = isLight ? Colors.black87 : Colors.white;
final textSecondary = isLight ? Colors.grey[700]! : Colors.grey[400]!;
final textMuted = isLight ? Colors.grey[600]! : Colors.grey[500]!;
DateTime dayOf(CalendarEvent e) =>
DateTime(e.startTime!.year, e.startTime!.month, e.startTime!.day);
final todayEvents = _events
.where((e) => e.startTime != null && dayOf(e).isAtSameMomentAs(today))
.toList();
final upcomingEvents = _events
.where((e) => e.startTime != null && dayOf(e).isAfter(today))
.toList();
// Build upcoming list grouped by month, each card carries its own date block
final upcomingWidgets = <Widget>[];
DateTime? lastDay;
for (final e in upcomingEvents) {
final day = dayOf(e);
final isNewMonth = lastDay == null ||
lastDay.month != day.month ||
lastDay.year != day.year;
final isNewDay = lastDay == null || !lastDay.isAtSameMomentAs(day);
if (isNewMonth) {
upcomingWidgets.add(Padding(
padding: EdgeInsets.fromLTRB(16, lastDay == null ? 4 : 18, 16, 8),
child: Text(
DateFormat('LLLL yyyy', locale).format(day).toUpperCase(),
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: textMuted,
letterSpacing: 1.5),
),
));
}
upcomingWidgets.add(Padding(
padding:
EdgeInsets.fromLTRB(16, isNewDay && !isNewMonth ? 10 : 0, 16, 8),
child: _buildEventCard(e, accentColor,
date: day, daysFromToday: day.difference(today).inDays),
));
lastDay = day;
}
return RefreshIndicator(
onRefresh: _loadEvents,
color: accentColor,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
// TODAY section
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSectionHeader(
_t('TODAY'),
accentColor,
textPrimary,
trailing: DateFormat('EEEE, d. MMMM', locale).format(now),
trailingColor: textSecondary,
),
const SizedBox(height: 10),
if (todayEvents.isEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
vertical: 14, horizontal: 14),
decoration: BoxDecoration(
color: textMuted.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Icon(Icons.event_busy, size: 18, color: textMuted),
const SizedBox(width: 10),
Text(_t('No events today'),
style:
TextStyle(fontSize: 13, color: textSecondary)),
],
),
)
else
...todayEvents.map((e) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: _buildEventCard(e, accentColor, highlight: true),
)),
],
),
),
if (upcomingEvents.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 10),
child:
_buildSectionHeader(_t('UPCOMING'), textMuted, textPrimary),
),
...upcomingWidgets,
],
if (_events.isEmpty) ...[
const SizedBox(height: 32),
Center(
child: Column(
children: [
Icon(Icons.event_available, size: 56, color: textMuted),
const SizedBox(height: 12),
Text(_t('No upcoming events'),
style: TextStyle(fontSize: 15, color: textMuted)),
const SizedBox(height: 6),
Text(_t('Pull down to refresh'),
style: TextStyle(fontSize: 13, color: textSecondary)),
],
),
),
],
const SizedBox(height: 24),
],
),
);
}
@override
Widget build(BuildContext context) {
final accentColor = _getAccentColor();
if (_isLoading && _events.isEmpty) {
return Scaffold(
backgroundColor: _backgroundColor,
body: Center(child: CircularProgressIndicator(color: accentColor)),
);
}
if (_errorMessage != null && _events.isEmpty) {
return Scaffold(
backgroundColor: _backgroundColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 64, color: accentColor),
const SizedBox(height: 24),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(_errorMessage!,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16, color: Surfaces.current.textSecondary)),
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _loadEvents,
icon: const Icon(Icons.refresh),
label: Text(_t('Retry')),
style: ElevatedButton.styleFrom(
backgroundColor: accentColor,
foregroundColor: Colors.white),
),
],
),
),
);
}
return Scaffold(
backgroundColor: _backgroundColor,
body: Column(
children: [
BarTabs(
tabs: [
BarTab(_t('Calendar'), Icons.calendar_month),
BarTab(_t('Contacts'), Icons.people),
],
selected: _showContacts ? 1 : 0,
onSelect: (i) => setState(() => _showContacts = i == 1),
),
// Body
Expanded(
child: _showContacts
? _buildContactsList()
: _buildCalendarView(accentColor),
),
],
),
);
}
}