581 lines
21 KiB
Dart
581 lines
21 KiB
Dart
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:intl/intl.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 '../widgets/section.dart';
|
||
import '../widgets/ui.dart';
|
||
import 'settings_screen.dart';
|
||
|
||
enum EventType {
|
||
regular, // dežurstvo
|
||
competition,
|
||
sestanek,
|
||
}
|
||
|
||
/// Koledar (club events: today, the week, upcoming) and Kontakti (members).
|
||
/// Only shown to club members.
|
||
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;
|
||
bool _showContacts = false;
|
||
String _query = '';
|
||
|
||
List<Contact> get _contacts => AppSettings.instance.clubContacts;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_loadEvents();
|
||
}
|
||
|
||
String _t(String key) => AppSettings.instance.t(key);
|
||
|
||
@override
|
||
void dispose() {
|
||
_calendarService.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
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> _launch(Uri uri) async {
|
||
try {
|
||
await launchUrl(uri);
|
||
} 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)),
|
||
);
|
||
}
|
||
|
||
// Avatar tint per member, from the design's six pairs (background, initials)
|
||
static (Color, Color) _avatar(Palette c, int i) {
|
||
const dark = [
|
||
(Color(0x2634CF8E), Color(0xFF7EE6B9)),
|
||
(Color(0x266EA8FF), Color(0xFFA9CBFF)),
|
||
(Color(0x26F2706A), Color(0xFFF7A6A2)),
|
||
(Color(0x26B28CFF), Color(0xFFD2BCFF)),
|
||
(Color(0x26F2C12E), Color(0xFFF6D366)),
|
||
(Color(0x263CC8D6), Color(0xFF8FE3EC)),
|
||
];
|
||
const light = [
|
||
(Color(0xFFE4F3EB), Color(0xFF0C6646)),
|
||
(Color(0xFFE7EEFB), Color(0xFF2D55A8)),
|
||
(Color(0xFFFBEAE4), Color(0xFFA3472B)),
|
||
(Color(0xFFF1EAFB), Color(0xFF6A43A8)),
|
||
(Color(0xFFFDF4D3), Color(0xFF7A5A00)),
|
||
(Color(0xFFE6F4F6), Color(0xFF1F6E7A)),
|
||
];
|
||
final list = c.isDark ? dark : light;
|
||
return list[i % list.length];
|
||
}
|
||
|
||
static String _initials(Contact contact) =>
|
||
'${contact.firstName.isEmpty ? '' : contact.firstName[0]}${contact.lastName.isEmpty ? '' : contact.lastName[0]}'.toUpperCase();
|
||
|
||
void _showContactPopup(BuildContext context, Contact contact, int index) {
|
||
final c = Palette.current;
|
||
final (bg, fg) = _avatar(c, index);
|
||
showAppSheet(
|
||
context,
|
||
builder: (sheet) => Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
CircleAvatar(
|
||
radius: 26,
|
||
backgroundColor: bg,
|
||
child: Text(_initials(contact), style: TextStyle(color: fg, fontSize: 18, fontWeight: FontWeight.w700)),
|
||
),
|
||
const SizedBox(width: 14),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(_capitalize(contact.fullName), style: TextStyle(color: c.ink, fontSize: 20, fontWeight: FontWeight.w700)),
|
||
if (contact.role.isNotEmpty) Text(contact.role, style: TextStyle(color: c.muted, fontSize: 13)),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 18),
|
||
_contactDetailRow(Icons.phone_outlined, _t('Phone'), contact.phone, () {
|
||
_copyToClipboard(contact.phone, _t('Phone'));
|
||
Navigator.pop(sheet);
|
||
}),
|
||
const SizedBox(height: 10),
|
||
_contactDetailRow(Icons.mail_outline_rounded, _t('Email'), contact.email.toLowerCase(), () {
|
||
_copyToClipboard(contact.email, _t('Email'));
|
||
Navigator.pop(sheet);
|
||
}),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _contactDetailRow(IconData icon, String label, String value, VoidCallback onCopy) {
|
||
final c = Palette.current;
|
||
return AppCard(
|
||
color: c.isDark ? c.card2 : c.card,
|
||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||
child: Row(
|
||
children: [
|
||
IconBadge(icon, size: 36),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(label, style: TextStyle(color: c.muted, fontSize: 11.5)),
|
||
Text(value,
|
||
style: TextStyle(color: c.ink, fontSize: 14.5, fontWeight: FontWeight.w600),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis),
|
||
],
|
||
),
|
||
),
|
||
CircleButton(icon: Icons.copy_rounded, size: 38, iconSize: 18, onTap: onCopy),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildContactsList() {
|
||
final c = Palette.current;
|
||
final q = _query.trim().toLowerCase();
|
||
final all = _contacts;
|
||
final shown = [
|
||
for (int i = 0; i < all.length; i++)
|
||
if (q.isEmpty || all[i].fullName.toLowerCase().contains(q) || all[i].role.toLowerCase().contains(q)) (i, all[i]),
|
||
];
|
||
return ListView(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24),
|
||
children: [
|
||
TextField(
|
||
onChanged: (v) => setState(() => _query = v),
|
||
style: TextStyle(color: c.ink, fontSize: 15),
|
||
decoration: InputDecoration(
|
||
hintText: _t('Search members …'),
|
||
prefixIcon: Icon(Icons.search_rounded, size: 20, color: c.muted),
|
||
fillColor: c.card,
|
||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide(color: c.line2)),
|
||
enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide(color: c.line2)),
|
||
),
|
||
),
|
||
SectionHeader('${_t('Members')} · ${all.length}'),
|
||
if (shown.isNotEmpty)
|
||
GroupCard(children: [
|
||
for (final (i, contact) in shown)
|
||
InkWell(
|
||
onTap: () => _showContactPopup(context, contact, i),
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 12, 12, 12),
|
||
child: Row(
|
||
children: [
|
||
CircleAvatar(
|
||
radius: 19,
|
||
backgroundColor: _avatar(c, i).$1,
|
||
child: Text(_initials(contact),
|
||
style: TextStyle(color: _avatar(c, i).$2, fontSize: 13, fontWeight: FontWeight.w700)),
|
||
),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(_capitalize(contact.fullName),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: c.ink)),
|
||
Text(contact.role.isNotEmpty ? contact.role : contact.phone,
|
||
maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)),
|
||
],
|
||
),
|
||
),
|
||
CircleButton(
|
||
icon: Icons.mail_outline_rounded,
|
||
size: 38,
|
||
iconSize: 18,
|
||
tooltip: _t('Email'),
|
||
onTap: () => _launch(Uri(scheme: 'mailto', path: contact.email)),
|
||
),
|
||
const SizedBox(width: 8),
|
||
CircleButton(
|
||
icon: Icons.call_outlined,
|
||
size: 38,
|
||
iconSize: 18,
|
||
color: c.accent,
|
||
background: c.accentSoft,
|
||
tooltip: _t('Phone'),
|
||
onTap: () => _launch(Uri(scheme: 'tel', path: contact.phone)),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
]),
|
||
],
|
||
);
|
||
}
|
||
|
||
// Type colours: duty blue, competition gold, meeting purple
|
||
(Color stripe, Color chipBg, Color chipFg) _eventColors(EventType type) {
|
||
final c = Palette.current;
|
||
return switch (type) {
|
||
EventType.competition => (c.gold, c.goldSoft, c.isDark ? c.goldInk : c.goldInk),
|
||
EventType.sestanek => (c.purple, c.purple.withValues(alpha: 0.15), c.isDark ? const Color(0xFFD2BCFF) : c.purple),
|
||
EventType.regular => (c.blue, c.blue.withValues(alpha: 0.15), c.isDark ? const Color(0xFFA9CBFF) : c.blue),
|
||
};
|
||
}
|
||
|
||
String _eventBadgeLabel(EventType type) => switch (type) {
|
||
EventType.competition => _t('COMPETITION'),
|
||
EventType.sestanek => _t('MEETING'),
|
||
EventType.regular => _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())}';
|
||
}
|
||
|
||
String _relative(int days) =>
|
||
days == 1 ? _t('Tomorrow') : _t('in {n} days').replaceAll('{n}', '$days');
|
||
|
||
// Card with the type's colour as a stripe on the left
|
||
Widget _eventCard(CalendarEvent event, {bool today = false, int daysFromToday = 0}) {
|
||
final type = _getEventType(event);
|
||
if (type == null) return const SizedBox();
|
||
final c = Palette.current;
|
||
final s = AppSettings.instance;
|
||
final (stripe, chipBg, chipFg) = _eventColors(type);
|
||
final hasLocation = event.location != null && event.location!.isNotEmpty;
|
||
final start = event.startTime?.toLocal();
|
||
|
||
return AppCard(
|
||
padding: EdgeInsets.zero,
|
||
child: IntrinsicHeight(
|
||
child: Row(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Container(width: 4, color: stripe),
|
||
Expanded(
|
||
child: Padding(
|
||
padding: EdgeInsets.fromLTRB(14, 12, 12, today ? 14 : 12),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
StatusChip(label: _eventBadgeLabel(type), color: chipFg, background: chipBg),
|
||
const Spacer(),
|
||
if (today)
|
||
StatusChip(
|
||
label: SettingsScreen.hoursBefore(s.reminderHours),
|
||
icon: Icons.notifications_none_rounded,
|
||
color: c.ink2,
|
||
background: c.tile,
|
||
)
|
||
else
|
||
Text(_relative(daysFromToday), style: TextStyle(fontSize: 12, color: c.muted)),
|
||
],
|
||
),
|
||
const SizedBox(height: 8),
|
||
Text(
|
||
event.summary ?? _t('Untitled Event'),
|
||
style: TextStyle(fontSize: today ? 17 : 15.5, fontWeight: FontWeight.w700, color: c.ink),
|
||
),
|
||
const SizedBox(height: 4),
|
||
if (today)
|
||
Wrap(
|
||
spacing: 16,
|
||
runSpacing: 4,
|
||
children: [
|
||
_meta(Icons.schedule_rounded, _timeText(event)),
|
||
if (hasLocation) _meta(Icons.place_outlined, event.location!),
|
||
],
|
||
)
|
||
else
|
||
Text(
|
||
[
|
||
if (start != null) DateFormat('EEE d. M.', s.dateLocale).format(start),
|
||
if (start != null && !event.isAllDay) DateFormat('H:mm').format(start),
|
||
if (hasLocation) event.location!,
|
||
].join(' · '),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 12, color: c.muted),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _meta(IconData icon, String text) {
|
||
final c = Palette.current;
|
||
return Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Icon(icon, size: 15, color: c.ink2),
|
||
const SizedBox(width: 5),
|
||
Flexible(child: Text(text, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink2))),
|
||
],
|
||
);
|
||
}
|
||
|
||
// Monday–Sunday of this week; today in the accent, a dot under days with events
|
||
Widget _weekStrip(DateTime today) {
|
||
final c = Palette.current;
|
||
final locale = AppSettings.instance.dateLocale;
|
||
final monday = today.subtract(Duration(days: today.weekday - 1));
|
||
bool hasEvent(DateTime d) => _events.any((e) {
|
||
final s = e.startTime?.toLocal();
|
||
return s != null && s.year == d.year && s.month == d.month && s.day == d.day;
|
||
});
|
||
return Row(
|
||
children: [
|
||
for (int i = 0; i < 7; i++) ...[
|
||
if (i > 0) const SizedBox(width: 6),
|
||
Expanded(
|
||
child: Builder(builder: (_) {
|
||
final d = monday.add(Duration(days: i));
|
||
final isToday = d == today;
|
||
final fg = isToday ? c.onAccent : c.ink;
|
||
return Container(
|
||
height: 62,
|
||
decoration: BoxDecoration(
|
||
color: isToday ? c.accent : c.card,
|
||
borderRadius: BorderRadius.circular(12),
|
||
border: isToday ? null : Border.all(color: c.line2),
|
||
),
|
||
child: Column(
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
children: [
|
||
Text(DateFormat('E', locale).format(d).substring(0, 1).toUpperCase(),
|
||
style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: isToday ? fg : c.muted)),
|
||
Text('${d.day}',
|
||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, height: 1.2, color: fg, fontFeatures: AppTheme.tnum)),
|
||
Container(
|
||
width: 5,
|
||
height: 5,
|
||
decoration: BoxDecoration(
|
||
color: hasEvent(d) ? (isToday ? c.onAccent : c.accent) : Colors.transparent,
|
||
shape: BoxShape.circle,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}),
|
||
),
|
||
],
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildCalendarView() {
|
||
final c = Palette.current;
|
||
final now = DateTime.now();
|
||
final today = DateTime(now.year, now.month, now.day);
|
||
final locale = AppSettings.instance.dateLocale;
|
||
|
||
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();
|
||
|
||
return RefreshIndicator(
|
||
onRefresh: _loadEvents,
|
||
child: ListView(
|
||
physics: const AlwaysScrollableScrollPhysics(),
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24),
|
||
children: [
|
||
_weekStrip(today),
|
||
SectionHeader('${_t('TODAY')} · ${DateFormat('EEEE d. M.', locale).format(now)}'),
|
||
if (todayEvents.isEmpty)
|
||
AppCard(
|
||
padding: const EdgeInsets.all(14),
|
||
child: Row(
|
||
children: [
|
||
Icon(Icons.event_busy_outlined, size: 18, color: c.muted),
|
||
const SizedBox(width: 10),
|
||
Text(_t('No events today'), style: TextStyle(fontSize: 13.5, color: c.muted)),
|
||
],
|
||
),
|
||
)
|
||
else
|
||
for (final e in todayEvents)
|
||
Padding(padding: const EdgeInsets.only(bottom: 10), child: _eventCard(e, today: true)),
|
||
if (upcomingEvents.isNotEmpty) ...[
|
||
SectionHeader(_t('UPCOMING')),
|
||
for (final e in upcomingEvents)
|
||
Padding(
|
||
padding: const EdgeInsets.only(bottom: 10),
|
||
child: _eventCard(e, daysFromToday: dayOf(e).difference(today).inDays),
|
||
),
|
||
],
|
||
if (_events.isEmpty) ...[
|
||
const SizedBox(height: 32),
|
||
EmptyState(icon: Icons.event_available_outlined, title: _t('No upcoming events'), hint: _t('Pull down to refresh')),
|
||
],
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
void _showNotifications() {
|
||
final s = AppSettings.instance;
|
||
showAppSheet(
|
||
context,
|
||
title: s.t('Notifications'),
|
||
builder: (sheet) => ListenableBuilder(
|
||
listenable: s,
|
||
builder: (context, _) => GroupCard(children: SettingsScreen.notificationTiles(context)),
|
||
),
|
||
);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return ListenableBuilder(
|
||
listenable: AppSettings.instance,
|
||
builder: (context, _) {
|
||
Widget body;
|
||
if (_showContacts) {
|
||
body = _buildContactsList();
|
||
} else if (_isLoading && _events.isEmpty) {
|
||
body = const Center(child: CircularProgressIndicator());
|
||
} else if (_errorMessage != null && _events.isEmpty) {
|
||
body = Center(
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(32),
|
||
child: EmptyState(
|
||
icon: Icons.cloud_off_rounded,
|
||
title: _t('Could not load the calendar'),
|
||
hint: _errorMessage,
|
||
action: SizedBox(
|
||
width: 180,
|
||
child: PrimaryButton(label: _t('Retry'), icon: Icons.refresh_rounded, height: 46, onTap: _loadEvents),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
} else {
|
||
body = _buildCalendarView();
|
||
}
|
||
|
||
return Column(
|
||
children: [
|
||
PageHeader(
|
||
title: _t('Calendar'),
|
||
action: CircleButton(icon: Icons.notifications_none_rounded, tooltip: _t('Notifications'), onTap: _showNotifications),
|
||
),
|
||
BarTabs(
|
||
tabs: [
|
||
BarTab(_t('Calendar'), Icons.calendar_today_outlined),
|
||
BarTab(_t('Contacts'), Icons.person_add_alt_outlined),
|
||
],
|
||
selected: _showContacts ? 1 : 0,
|
||
onSelect: (i) => setState(() => _showContacts = i == 1),
|
||
),
|
||
Expanded(child: body),
|
||
],
|
||
);
|
||
},
|
||
);
|
||
}
|
||
}
|