import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_auth/firebase_auth.dart';

/// Service for managing persistent user sessions
class SessionService {
  static const String _rememberMeKey = 'remember_me';
  static const String _userEmailKey = 'user_email';
  static const String _userDisplayNameKey = 'user_display_name';
  static const String _lastLoginTimeKey = 'last_login_time';

  /// Save session preferences when user chooses "Remember me"
  static Future<void> saveSession({
    required bool rememberMe,
    required String email,
    String? displayName,
  }) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      // Save remember me preference
      await prefs.setBool(_rememberMeKey, rememberMe);
      
      if (rememberMe) {
        // Save user details for auto-login
        await prefs.setString(_userEmailKey, email);
        if (displayName != null) {
          await prefs.setString(_userDisplayNameKey, displayName);
        }
        await prefs.setInt(_lastLoginTimeKey, DateTime.now().millisecondsSinceEpoch);
      } else {
        // Clear saved session if remember me is unchecked
        await clearSession();
      }
      
      print('DEBUG: Session saved - Remember me: $rememberMe, Email: $email');
    } catch (e) {
      print('DEBUG: Error saving session: $e');
    }
  }

  /// Check if user should be automatically logged in
  static Future<Map<String, dynamic>> shouldAutoLogin() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      final rememberMe = prefs.getBool(_rememberMeKey) ?? false;
      final email = prefs.getString(_userEmailKey);
      final displayName = prefs.getString(_userDisplayNameKey);
      final lastLoginTime = prefs.getInt(_lastLoginTimeKey);
      
      print('DEBUG: Auto-login check - Remember me: $rememberMe, Email: $email');
      
      if (rememberMe && email != null) {
        // Check if session is not too old (optional: 30 days)
        if (lastLoginTime != null) {
          final lastLogin = DateTime.fromMillisecondsSinceEpoch(lastLoginTime);
          final now = DateTime.now();
          final daysSinceLogin = now.difference(lastLogin).inDays;
          
          if (daysSinceLogin <= 30) {
            return {
              'shouldAutoLogin': true,
              'email': email,
              'displayName': displayName,
            };
          } else {
            print('DEBUG: Session too old, clearing session');
            await clearSession();
          }
        }
      }
      
      return {'shouldAutoLogin': false};
    } catch (e) {
      print('DEBUG: Error checking auto-login: $e');
      return {'shouldAutoLogin': false};
    }
  }

  /// Clear saved session data
  static Future<void> clearSession() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_rememberMeKey);
      await prefs.remove(_userEmailKey);
      await prefs.remove(_userDisplayNameKey);
      await prefs.remove(_lastLoginTimeKey);
      
      print('DEBUG: Session cleared');
    } catch (e) {
      print('DEBUG: Error clearing session: $e');
    }
  }

  /// Get current session info
  static Future<Map<String, dynamic>> getCurrentSession() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      return {
        'rememberMe': prefs.getBool(_rememberMeKey) ?? false,
        'email': prefs.getString(_userEmailKey),
        'displayName': prefs.getString(_userDisplayNameKey),
        'lastLoginTime': prefs.getInt(_lastLoginTimeKey),
      };
    } catch (e) {
      print('DEBUG: Error getting current session: $e');
      return {};
    }
  }

  /// Update session with current Firebase user
  static Future<void> updateSessionWithCurrentUser() async {
    try {
      final user = FirebaseAuth.instance.currentUser;
      if (user != null) {
        final currentSession = await getCurrentSession();
        if (currentSession['rememberMe'] == true) {
          await saveSession(
            rememberMe: true,
            email: user.email ?? '',
            displayName: user.displayName,
          );
        }
      }
    } catch (e) {
      print('DEBUG: Error updating session with current user: $e');
    }
  }
}
