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 '../services/google_calendar_service.dart'; import '../services/notification_service.dart'; import '../utils/translations.dart'; import '../utils/target_colors.dart'; class Contact { final String firstName; final String lastName; final String phone; final String email; Contact({ required this.firstName, required this.lastName, required this.phone, required this.email, }); String get fullName => '$firstName $lastName'; } enum EventType { regular, competition, sestanek, } class CalendarScreen extends StatefulWidget { const CalendarScreen({super.key}); @override State createState() => _CalendarScreenState(); } class _CalendarScreenState extends State { final GoogleCalendarService _calendarService = GoogleCalendarService(); bool _isLoading = false; List _events = []; String? _errorMessage; String _bulletColor = 'Blue'; String _selectedLanguage = 'English'; bool _showContacts = false; late Color _backgroundColor; final List _contacts = [ Contact(firstName: 'Domen', lastName: 'Pleterski', phone: '051227764', email: 'info@bl3k.com'), Contact(firstName: 'Ivan', lastName: 'Tandler', phone: '040471258', email: 'ivan.tandler@gmail.com'), Contact(firstName: 'Jože', lastName: 'Verhnjak', phone: '041443463', email: 'joze.verhnjak@gmail.com'), Contact(firstName: 'Branko', lastName: 'Pokeržnik', phone: '041291001', email: 'pokerznik.helena@gmail.com'), Contact(firstName: 'Franc', lastName: 'Žigart', phone: '041439597', email: 'franc.zigart@gmail.com'), Contact(firstName: 'Janez', lastName: 'Božič', phone: '041551704', email: 'janbozic@gmail.com'), Contact(firstName: 'Mitja', lastName: 'Čeh', phone: '070550383', email: 'mekabara@gmail.com'), Contact(firstName: 'Rado', lastName: 'Keter', phone: '041324529', email: 'rado.keter@gmail.com'), Contact(firstName: 'Karli', lastName: 'Proje', phone: '040424951', email: 'karl.project@gmail.com'), Contact(firstName: 'Jan', lastName: 'Pleterski', phone: '041842063', email: 'jan.pleterski1997@gmail.com'), Contact(firstName: 'Silvo', lastName: 'Poročnik', phone: '040860618', email: 'skobar.silvo@gmail.com'), Contact(firstName: 'Dušan', lastName: 'Onuk', phone: '070448303', email: 'dusan.onuk@gmail.com'), Contact(firstName: 'Matjaž', lastName: 'Pleterski', phone: '041603859', email: 'matjaz.pleterski@gmail.com'), Contact(firstName: 'Marko', lastName: 'Blimen', phone: '031610857', email: 'blimenmarko@gmail.com'), Contact(firstName: 'Doris', lastName: 'Fesel', phone: '070373987', email: 'doris.fesel@gmail.com'), ]; @override void initState() { super.initState(); initializeDateFormatting('sl_SI', null); _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); _loadBulletColor(); _loadLanguage(); _loadSelectedTargetColor(); _loadEvents(); } String _t(String key) => AppTranslations.translate(key, _selectedLanguage); Future _loadLanguage() async { final prefs = await SharedPreferences.getInstance(); setState(() => _selectedLanguage = prefs.getString('language') ?? 'English'); } Future _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 _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 _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 _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) { return 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( onTap: () => _makePhoneCall(contact.phone), onLongPress: () => _showContactPopup(context, contact), child: Container( margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(12), boxShadow: [ BoxShadow(color: Colors.grey.withValues(alpha: 0.3), blurRadius: 8, 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: const TextStyle(fontSize: 12, color: Colors.black87, 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: const TextStyle(fontSize: 12, color: Colors.black87, 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())}'; } Widget _buildEventCard(CalendarEvent event, Color accentColor, {bool highlight = false}) { final eventType = _getEventType(event); if (eventType == null) return const SizedBox(); final color = _eventColor(eventType, accentColor); final hasLocation = event.location != null && event.location!.isNotEmpty; return RepaintBoundary( child: Container( decoration: BoxDecoration( color: Colors.grey[300], 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 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: Colors.grey[700]), const SizedBox(width: 4), Text( _timeText(event), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.grey[800]), ), ], ), const SizedBox(height: 8), Text( event.summary ?? _t('Untitled Event'), style: TextStyle( fontSize: highlight ? 16 : 14, fontWeight: FontWeight.w700, color: Colors.grey[900], ), ), if (hasLocation) ...[ const SizedBox(height: 4), Row( children: [ Icon(Icons.location_on, size: 13, color: Colors.grey[600]), const SizedBox(width: 4), Expanded( child: Text( event.location!, style: TextStyle(fontSize: 12, color: Colors.grey[700]), 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 _buildDateColumn(DateTime date, int daysFromToday, Color accentColor, bool isLight) { final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US'; final relative = daysFromToday == 1 ? _t('Tomorrow') : _t('in {n} days').replaceAll('{n}', '$daysFromToday'); return SizedBox( width: 48, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( DateFormat('EEE', locale).format(date).toUpperCase(), style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700, color: isLight ? Colors.grey[700] : Colors.grey[400], letterSpacing: 0.8), ), Text( DateFormat('d').format(date), style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: isLight ? Colors.black87 : Colors.white, height: 1.15), ), Text( relative, textAlign: TextAlign.center, style: TextStyle( fontSize: 9, fontWeight: daysFromToday == 1 ? FontWeight.bold : FontWeight.w500, color: daysFromToday == 1 ? accentColor : (isLight ? Colors.grey[600] : Colors.grey[500]), ), ), ], ), ); } 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, date column shown once per day final upcomingWidgets = []; 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(12, isNewDay && !isNewMonth ? 10 : 0, 16, 8), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ isNewDay ? _buildDateColumn(day, day.difference(today).inDays, accentColor, isLight) : const SizedBox(width: 48), const SizedBox(width: 10), Expanded(child: _buildEventCard(e, accentColor)), ], ), )); 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: const TextStyle(fontSize: 16, color: Colors.white70)), ), 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: [ // Tab bar Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: BoxDecoration( color: Colors.grey[900], ), child: Row( children: [ _buildTab(_t('Calendar'), Icons.calendar_month, !_showContacts, () => setState(() => _showContacts = false)), const SizedBox(width: 6), _buildTab(_t('Contacts'), Icons.people, _showContacts, () => setState(() => _showContacts = true)), ], ), ), // Body Expanded( child: _showContacts ? _buildContactsList() : _buildCalendarView(accentColor), ), ], ), ); } Widget _buildTab(String label, IconData icon, bool active, VoidCallback onTap) { return Expanded( child: GestureDetector( onTap: onTap, child: Container( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8), decoration: BoxDecoration( color: active ? Colors.white : Colors.transparent, borderRadius: BorderRadius.circular(10), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Icon(icon, color: active ? Colors.black : Colors.grey[400], size: 18), const SizedBox(width: 6), Text( label, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: active ? Colors.black : Colors.grey[400]), ), ], ), ), ), ); } }