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/locations_model.dart';

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

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

  // Get locations by district ID
  Future<List<LocationModel>> getLocationsByDistrictId(
    String districtId,
  ) async {
    try {
      final response = await _supabase
          .from('locations')
          .select(
            '*, event(*), incident_logs(*), crime_incidents(*), patrol_units(*)',
          )
          .eq('district_id', districtId);

      final data = response as List;
      return data.map((json) => LocationModel.fromJson(json)).toList();
    } catch (e) {
      _log.e('Error fetching locations for district $districtId: $e');
      throw Exception('Failed to load locations: $e');
    }
  }

  // Get location by ID
  Future<LocationModel> getLocationById(String locationId) async {
    try {
      final response =
          await _supabase
              .from('locations')
              .select(
                '*, event(*), incident_logs(*), crime_incidents(*), patrol_units(*)',
              )
              .eq('id', locationId)
              .single();

      return LocationModel.fromJson(response);
    } catch (e) {
      _log.e('Error fetching location $locationId: $e');
      throw Exception('Failed to load location details: $e');
    }
  }

  // Get locations within a radius (kilometers) of a point
  Future<List<LocationModel>> getNearbyLocations(
    double latitude,
    double longitude,
    double radiusKm,
  ) async {
    try {
      // Use PostGIS to find locations within the radius
      final response = await _supabase.rpc(
        'locations_within_radius',
        params: {
          'lat': latitude,
          'lng': longitude,
          'radius': radiusKm * 1000, // Convert to meters
        },
      );

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

  // Add a new location
  Future<LocationModel> addLocation({
    required String districtId,
    required String eventId,
    required double latitude,
    required double longitude,
    String? address,
    String? type,
  }) async {
    try {
      final data = {
        'district_id': districtId,
        'event_id': eventId,
        'latitude': latitude,
        'longitude': longitude,
        'address': address,
        'type': type,
      };

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

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