import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/cores/services/supabase_service.dart';
import 'package:sigap/src/features/map/data/models/models/location_logs_model.dart';

class LocationLogsRepository extends GetxController {
  static LocationLogsRepository get instance => Get.find();

  final _supabase = SupabaseService.instance.client;
  final _log = Get.find<Logger>();

  // Get location logs for a specific user
  Future<List<LocationLogModel>> getUserLocationLogs(
    String userId, {
    int limit = 50,
  }) async {
    try {
      final response = await _supabase
          .from('location_logs')
          .select('*, users(*)')
          .eq('user_id', userId)
          .order('timestamp', ascending: false)
          .limit(limit);

      final data = response as List;
      return data.map((json) => LocationLogModel.fromJson(json)).toList();
    } catch (e) {
      _log.e('Error fetching location logs for user $userId: $e');
      throw Exception('Failed to load location logs: $e');
    }
  }

  // Add a new location log
  Future<LocationLogModel> addLocationLog({
    required String userId,
    required double latitude,
    required double longitude,
    String? description,
  }) async {
    try {
      final data = {
        'user_id': userId,
        'latitude': latitude,
        'longitude': longitude,
        'timestamp': DateTime.now().toIso8601String(),
        'description': description,
      };

      final response =
          await _supabase
              .from('location_logs')
              .insert(data)
              .select('*, users(*)')
              .single();

      return LocationLogModel.fromJson(response);
    } catch (e) {
      _log.e('Error adding location log: $e');
      throw Exception('Failed to add location log: $e');
    }
  }

  // Get recent location logs for all users
  Future<List<LocationLogModel>> getRecentLocationLogs({
    int limit = 100,
  }) async {
    try {
      final response = await _supabase
          .from('location_logs')
          .select('*, users(*)')
          .order('timestamp', ascending: false)
          .limit(limit);

      final data = response as List;
      return data.map((json) => LocationLogModel.fromJson(json)).toList();
    } catch (e) {
      _log.e('Error fetching recent location logs: $e');
      throw Exception('Failed to load recent location logs: $e');
    }
  }

  // Get location logs within a time range
  Future<List<LocationLogModel>> getLocationLogsInRange(
    DateTime start,
    DateTime end,
  ) async {
    try {
      final response = await _supabase
          .from('location_logs')
          .select('*, users(*)')
          .gte('timestamp', start.toIso8601String())
          .lte('timestamp', end.toIso8601String())
          .order('timestamp', ascending: true);

      final data = response as List;
      return data.map((json) => LocationLogModel.fromJson(json)).toList();
    } catch (e) {
      _log.e('Error fetching location logs in range: $e');
      throw Exception('Failed to load location logs in range: $e');
    }
  }
}
