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

class AuthServices {
  final SupabaseClient _supabase = Supabase.instance.client;
  
  // Sign in with email and password
  Future<AuthResponse> signInWithEmailPassword(
    String email, String password) async {
      try {
        // Tambahkan timeout untuk mencegah permintaan menggantung
        final response = await _supabase.auth.signInWithPassword(
          email: email,
          password: password)
          .timeout(
            const Duration(seconds: 15),
            onTimeout: () {
              throw TimeoutException('Koneksi timeout. Silakan coba lagi nanti.');
            },
          );
          
        return response;
      } catch (e) {
        debugPrint('Error saat login: $e');
        
        // Re-throw exception untuk ditangani di UI
        rethrow;
      }
    }

  // Sign Up with email and password
  Future<AuthResponse> signUpWithEmailPassword(
    String email, String password) async {
      final response = await _supabase.auth.signUp(
        email: email,
        password: password);
        
      return response;
    }

  // Sign Out 
  Future<void> signOut() async {
    await _supabase.auth.signOut();
  }
  
  // Get current user ID
  String? getCurrentUserId() {
    final session = _supabase.auth.currentSession;
    final user = session?.user;
    return user?.id;
  }
  
  // Request password reset (sends email with OTP)
  Future<void> forgotPassword(String email, {String? redirectUrl}) async {
    try {
      await _supabase.auth.resetPasswordForEmail(
        email,
        redirectTo: redirectUrl,
      );
    } catch (e) {
      debugPrint('Error sending password reset email: $e');
      throw Exception('Gagal mengirim email reset password: $e');
    }
  }
  
  // Verify OTP for password reset or signup
  Future<AuthResponse> verifyOTP({
    required String email, 
    required String token, 
    required OtpType type,
  }) async {
    try {
      final response = await _supabase.auth.verifyOTP(
        email: email,
        token: token,
        type: type,
      );
      
      return response;
    } catch (e) {
      debugPrint('Error verifying OTP: $e');
      throw Exception('Verifikasi OTP gagal: $e');
    }
  }
  
  // Reset password (after OTP verification)
  Future<void> resetPassword(String newPassword) async {
    try {
      await _supabase.auth.updateUser(
        UserAttributes(password: newPassword),
      );
    } catch (e) {
      debugPrint('Error resetting password: $e');
      throw Exception('Gagal mengubah password: $e');
    }
  }
  
  // Check if user is logged in (without checking timeout)
  bool isUserLoggedIn() {
    return _supabase.auth.currentSession != null;
  }
  
  // Get current authenticated user
  User? getCurrentUser() {
    return _supabase.auth.currentUser;
  }

  // Get current user email
  String? getCurrentUserEmail() {
    final session = _supabase.auth.currentSession;
    final user = session?.user;
    return user?.email;
  }
}