import 'package:flutter/material.dart';
import 'dart:async';
import 'package:tugas_akhir_supabase/services/session_manager.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

/// Mixin untuk memeriksa status session di halaman-halaman utama aplikasi
mixin SessionCheckerMixin<T extends StatefulWidget> on State<T> {
  bool _isCheckingSession = false;

  /// Initialize session checking
  void initSessionChecking() {
    debugPrint('SessionChecker: Initializing session checking');
    // Check session on init
    WidgetsBinding.instance.addPostFrameCallback((_) {
      checkSessionStatus();
    });
  }

  /// Dispose session checking
  void disposeSessionChecking() {
    debugPrint('SessionChecker: Disposing session checking');
    stopPeriodicSessionCheck();
  }

  /// Update user activity
  Future<void> updateUserActivity() async {
    try {
      await SessionManager.updateLastUserInteraction();
      debugPrint('SessionChecker: User activity updated');
    } catch (e) {
      debugPrint('SessionChecker: Error updating user activity: $e');
    }
  }

  /// Periksa status session saat halaman dibuka
  Future<void> checkSessionStatus() async {
    if (_isCheckingSession) return;
    _isCheckingSession = true;

    try {
      // Jangan cek session jika user belum login
      final currentUser = Supabase.instance.client.auth.currentUser;
      if (currentUser == null) {
        debugPrint('SessionChecker: No current user, skipping session check');
        _isCheckingSession = false;
        return;
      }

      // Only check session if user is actually logged in
      final currentSession = Supabase.instance.client.auth.currentSession;
      if (currentSession == null) {
        debugPrint(
          'SessionChecker: No current session, skipping session check',
        );
        _isCheckingSession = false;
        return;
      }

      debugPrint(
        'SessionChecker: Checking session for user: ${currentUser.id}',
      );

      // Tambahkan timeout untuk mencegah blocking
      final isValid = await SessionManager.isSessionValid().timeout(
        const Duration(seconds: 3),
        onTimeout: () {
          debugPrint('SessionChecker: Session check timed out');
          return true; // Assume valid on timeout
        },
      );

      debugPrint('SessionChecker: Session validity result: $isValid');

      // Update user interaction timestamp
      await SessionManager.updateLastUserInteraction();

      if (!isValid) {
        debugPrint(
          'SessionChecker: Session invalid, but continuing in permissive mode',
        );
        // In permissive mode, don't force logout
        return;
      }

      debugPrint('SessionChecker: Session is valid');
    } catch (e) {
      debugPrint('SessionChecker: Error checking session: $e');
      // In permissive mode, don't force logout on error
    } finally {
      _isCheckingSession = false;
    }
  }

  /// Periksa session secara berkala (DISABLED untuk permissive mode)
  void startPeriodicSessionCheck() {
    debugPrint(
      'SessionChecker: Periodic session check DISABLED for permissive mode',
    );
    // No periodic checks in permissive mode
  }

  /// Stop periodic session check
  void stopPeriodicSessionCheck() {
    debugPrint('SessionChecker: Stopping periodic session check');
    // Nothing to stop in permissive mode
  }

  @override
  void initState() {
    super.initState();
    // Check session on init
    WidgetsBinding.instance.addPostFrameCallback((_) {
      checkSessionStatus();
    });
  }

  @override
  void dispose() {
    stopPeriodicSessionCheck();
    super.dispose();
  }
}
