import 'dart:io'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../features/events/services/events_service.dart'; import '../features/events/models/event_models.dart'; import 'learn_more_screen.dart'; import 'settings_screen.dart'; // <- added import import '../core/app_decoration.dart'; class ProfileScreen extends StatefulWidget { const ProfileScreen({Key? key}) : super(key: key); @override State createState() => _ProfileScreenState(); } class _ProfileScreenState extends State { String _username = ''; String _email = 'not provided'; String _profileImage = ''; // per-account stored path or URL (may be empty) final ImagePicker _picker = ImagePicker(); final EventsService _eventsService = EventsService(); // events coming from backend List _upcomingEvents = []; List _pastEvents = []; bool _loadingEvents = true; @override void initState() { super.initState(); _loadProfile(); } /// Load profile for the currently signed-in account. Future _loadProfile() async { final prefs = await SharedPreferences.getInstance(); // current_email marks the active account (set at login/register) final currentEmail = prefs.getString('current_email') ?? prefs.getString('email') ?? ''; _email = currentEmail.isNotEmpty ? currentEmail : 'not provided'; // per-account display name key final displayKey = currentEmail.isNotEmpty ? 'display_name_$currentEmail' : 'display_name'; final profileImageKey = currentEmail.isNotEmpty ? 'profileImage_$currentEmail' : 'profileImage'; // Prefer per-account display_name, else fallback to email _username = prefs.getString(displayKey) ?? prefs.getString('display_name') ?? _email; _profileImage = prefs.getString(profileImageKey) ?? prefs.getString('profileImage') ?? ''; // load events for this account's pincode (or default) await _loadEventsForProfile(prefs); if (mounted) setState(() {}); } Future _loadEventsForProfile([SharedPreferences? prefs]) async { setState(() { _loadingEvents = true; _upcomingEvents = []; _pastEvents = []; }); prefs ??= await SharedPreferences.getInstance(); final pincode = prefs.getString('pincode') ?? 'all'; try { final events = await _eventsService.getEventsByPincode(pincode); final now = DateTime.now(); final upcoming = []; final past = []; DateTime? tryParseDate(String? s) { if (s == null) return null; try { return DateTime.tryParse(s); } catch (_) { return null; } } for (final e in events) { final parsed = tryParseDate(e.startDate); if (parsed == null) { upcoming.add(e); } else { if (parsed.isBefore(DateTime(now.year, now.month, now.day))) { past.add(e); } else { upcoming.add(e); } } } upcoming.sort((a, b) { final da = tryParseDate(a.startDate) ?? DateTime(9999); final db = tryParseDate(b.startDate) ?? DateTime(9999); return da.compareTo(db); }); past.sort((a, b) { final da = tryParseDate(a.startDate) ?? DateTime(0); final db = tryParseDate(b.startDate) ?? DateTime(0); return db.compareTo(da); }); if (mounted) { setState(() { _upcomingEvents = upcoming; _pastEvents = past; }); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to load events: $e'))); } } finally { if (mounted) setState(() => _loadingEvents = false); } } Future _saveProfile(String name, String email, String profileImage) async { final prefs = await SharedPreferences.getInstance(); final currentEmail = prefs.getString('current_email') ?? prefs.getString('email') ?? email; final displayKey = currentEmail.isNotEmpty ? 'display_name_$currentEmail' : 'display_name'; final profileImageKey = currentEmail.isNotEmpty ? 'profileImage_$currentEmail' : 'profileImage'; await prefs.setString(displayKey, name); await prefs.setString(profileImageKey, profileImage); // update 'email' canonical pointer and 'current_email' (defensive) await prefs.setString('email', currentEmail); await prefs.setString('current_email', currentEmail); setState(() { _username = name; _email = currentEmail.isNotEmpty ? currentEmail : 'not provided'; _profileImage = profileImage; }); } // ---------- Image picking / manual path ---------- Future _pickFromGallery() async { try { final XFile? xfile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 85); if (xfile == null) return; if (kIsWeb) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Use "Enter Asset Path" on web/desktop or add server URL.'))); return; } final String path = xfile.path; await _saveProfile(_username, _email, path); } catch (e) { debugPrint('Image pick error: $e'); ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to pick image: $e'))); } } Future _enterAssetPathDialog() async { final ctl = TextEditingController(text: _profileImage); final result = await showDialog( context: context, builder: (ctx) { final theme = Theme.of(ctx); return AlertDialog( title: const Text('Enter image path or URL'), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: ctl, decoration: const InputDecoration( labelText: 'Asset path (e.g. assets/images/profile.jpg) or URL', ), ), const SizedBox(height: 8), Text( 'Use an asset path (for bundled images) or an https:// URL (web).', style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor), ), ], ), actions: [ TextButton(onPressed: () => Navigator.of(ctx).pop(null), child: const Text('Cancel')), ElevatedButton(onPressed: () => Navigator.of(ctx).pop(ctl.text.trim()), child: const Text('Use')), ], ); }, ); if (result == null || result.isEmpty) return; await _saveProfile(_username, _email, result); } Future _openEditDialog() async { final nameCtl = TextEditingController(text: _username); final emailCtl = TextEditingController(text: _email); showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: Colors.transparent, builder: (ctx) { final theme = Theme.of(ctx); return DraggableScrollableSheet( expand: false, initialChildSize: 0.44, minChildSize: 0.28, maxChildSize: 0.92, builder: (context, scrollController) { return Container( padding: const EdgeInsets.fromLTRB(18, 14, 18, 18), decoration: BoxDecoration( color: theme.cardColor, borderRadius: const BorderRadius.vertical(top: Radius.circular(20)), ), child: SingleChildScrollView( controller: scrollController, child: Column( children: [ Container(width: 48, height: 6, decoration: BoxDecoration(color: theme.dividerColor, borderRadius: BorderRadius.circular(6))), const SizedBox(height: 12), Row( children: [ Text('Edit profile', style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold)), const Spacer(), IconButton( icon: const Icon(Icons.photo_camera), onPressed: () async { Navigator.of(context).pop(); // close sheet then launch picker to avoid nested modal issues await _pickFromGallery(); }, ), IconButton( icon: const Icon(Icons.link), onPressed: () { Navigator.of(context).pop(); _enterAssetPathDialog(); }, ), ], ), const SizedBox(height: 8), TextField(controller: nameCtl, decoration: InputDecoration(labelText: 'Name', filled: true, fillColor: theme.cardColor, border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)))), const SizedBox(height: 8), TextField(controller: emailCtl, decoration: InputDecoration(labelText: 'Email', filled: true, fillColor: theme.cardColor, border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)))), const SizedBox(height: 14), Row( children: [ const Spacer(), TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')), const SizedBox(width: 8), ElevatedButton( onPressed: () async { final newName = nameCtl.text.trim().isEmpty ? _email : nameCtl.text.trim(); final newEmail = emailCtl.text.trim().isEmpty ? _email : emailCtl.text.trim(); // If user changes email here (edge-case) we will treat newEmail as current account pointer. await _saveProfile(newName, newEmail, _profileImage); Navigator.of(context).pop(); }, child: const Text('Save'), ), ], ), const SizedBox(height: 8), Text( 'Tip: tap the camera icon to pick from gallery (mobile). Or tap the link icon to paste an asset path or URL.', style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor), ), ], ), ), ); }, ); }, ); } // ---------- UI helpers ---------- Widget _topIcon(IconData icon, {VoidCallback? onTap}) { final theme = Theme.of(context); return InkWell( onTap: onTap ?? () {}, borderRadius: BorderRadius.circular(12), child: Container( width: 44, height: 44, decoration: BoxDecoration(color: theme.cardColor.withOpacity(0.6), borderRadius: BorderRadius.circular(12)), child: Icon(icon, color: theme.iconTheme.color), ), ); } Widget _eventListTileFromModel(EventModel ev, {bool faded = false}) { final theme = Theme.of(context); final title = ev.title ?? ev.name ?? ''; final dateLabel = (ev.startDate != null && ev.endDate != null && ev.startDate == ev.endDate) ? ev.startDate! : ((ev.startDate != null && ev.endDate != null) ? '${ev.startDate} - ${ev.endDate}' : (ev.startDate ?? '')); final location = ev.place ?? ''; final imageUrl = (ev.thumbImg != null && ev.thumbImg!.isNotEmpty) ? ev.thumbImg! : (ev.images.isNotEmpty ? ev.images.first.image : null); final titleStyle = theme.textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w600, color: faded ? theme.hintColor : theme.textTheme.bodyLarge?.color); final subtitleStyle = theme.textTheme.bodySmall?.copyWith(fontSize: 13, color: faded ? theme.hintColor.withOpacity(0.7) : theme.hintColor); Widget leadingWidget() { if (imageUrl != null && imageUrl.trim().isNotEmpty) { if (imageUrl.startsWith('http')) { return ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.network(imageUrl, width: 56, height: 56, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)))); } else if (!kIsWeb) { final path = imageUrl; if (path.startsWith('/') || path.contains(Platform.pathSeparator)) { final file = File(path); if (file.existsSync()) { return ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.file(file, width: 56, height: 56, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)))); } else { return ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.asset(imageUrl, width: 56, height: 56, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)))); } } else { return ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.asset(imageUrl, width: 56, height: 56, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)))); } } else { return ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.asset(imageUrl, width: 56, height: 56, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)))); } } return Container(width: 56, height: 56, color: Theme.of(context).dividerColor, child: Icon(Icons.image, color: Theme.of(context).hintColor)); } return Container( margin: const EdgeInsets.symmetric(vertical: 8), decoration: BoxDecoration( color: Theme.of(context).cardColor, borderRadius: BorderRadius.circular(14), boxShadow: [BoxShadow(color: Theme.of(context).shadowColor.withOpacity(0.06), blurRadius: 10, offset: const Offset(0, 6))], ), child: ListTile( onTap: () { if (ev.id != null) { Navigator.of(context).push(MaterialPageRoute(builder: (_) => LearnMoreScreen(eventId: ev.id))); } }, contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), leading: ClipRRect(borderRadius: BorderRadius.circular(8), child: leadingWidget()), title: Text(title, style: titleStyle), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 6), Text(dateLabel, style: subtitleStyle), const SizedBox(height: 2), Text(location, style: subtitleStyle), ], ), trailing: Container( width: 40, height: 40, decoration: BoxDecoration(color: Theme.of(context).colorScheme.primary.withOpacity(0.12), borderRadius: BorderRadius.circular(10)), child: Icon(Icons.qr_code_scanner, color: Theme.of(context).colorScheme.primary), ), ), ); } Widget _buildProfileAvatar() { final path = _profileImage.trim(); if (path.startsWith('http')) { return ClipOval(child: Image.network(path, width: 96, height: 96, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 48, color: Colors.grey))); } if (kIsWeb) { return ClipOval(child: Image.asset(path.isNotEmpty ? path : 'assets/images/profile.jpg', width: 96, height: 96, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 48, color: Colors.grey))); } if (path.isNotEmpty && (path.startsWith('/') || path.contains(Platform.pathSeparator))) { final file = File(path); if (file.existsSync()) { return ClipOval(child: Image.file(file, width: 96, height: 96, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 48, color: Colors.grey))); } else { return ClipOval(child: Image.asset('assets/images/profile.jpg', width: 96, height: 96, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 48, color: Colors.grey))); } } return ClipOval(child: Image.asset('assets/images/profile.jpg', width: 96, height: 96, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 48, color: Colors.grey))); } @override Widget build(BuildContext context) { final theme = Theme.of(context); final gradient = const LinearGradient(colors: [Color(0xFF0B63D6), Color(0xFF1449B8)], begin: Alignment.topLeft, end: Alignment.bottomRight); return Scaffold( backgroundColor: theme.scaffoldBackgroundColor, body: Column( children: [ Container( width: double.infinity, decoration: AppDecoration.blueGradient.copyWith(borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(24), bottomRight: Radius.circular(24))), child: SafeArea( bottom: false, child: Padding( padding: const EdgeInsets.fromLTRB(20, 18, 20, 20), child: Column( children: [ Row( children: [ const Expanded(child: SizedBox()), Text('Profile', style: theme.textTheme.titleMedium?.copyWith(color: Colors.white, fontWeight: FontWeight.w600)), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ GestureDetector( onTap: () => _openEditDialog(), child: Container(margin: const EdgeInsets.only(right: 10), width: 40, height: 40, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(10)), child: const Icon(Icons.edit, color: Colors.white)), ), // <-- REPLACED the reminder icon with settings icon and navigation GestureDetector( onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const SettingsScreen())), child: Container(width: 40, height: 40, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(10)), child: const Icon(Icons.settings, color: Colors.white)), ), ], ), ), ], ), const SizedBox(height: 18), GestureDetector( onTap: () => _openEditDialog(), child: CircleAvatar(radius: 48, backgroundColor: Colors.white, child: _buildProfileAvatar()), ), const SizedBox(height: 12), Text(_username, style: theme.textTheme.titleLarge?.copyWith(color: Colors.white, fontWeight: FontWeight.bold)), const SizedBox(height: 6), Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(16)), child: Text(_email, style: const TextStyle(color: Colors.white70))), ], ), ), ), ), Expanded( child: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(18, 18, 18, 24), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Removed Upcoming Events section — kept only Past Events below Text('Past Events', style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold)), const SizedBox(height: 12), if (_loadingEvents) const SizedBox.shrink() else if (_pastEvents.isEmpty) Padding( padding: const EdgeInsets.symmetric(vertical: 12), child: Text('No past events', style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor)), ) else Column(children: _pastEvents.map((e) => _eventListTileFromModel(e, faded: true)).toList()), const SizedBox(height: 28), ], ), ), ), ], ), ); } }