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

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

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

  // Get geographic data by district ID
  Future<List<GeographicModel>> getGeographicsByDistrictId(
    String districtId,
  ) async {
    try {
      final response = await _supabase
          .from('geographics')
          .select('*, districts(*)')
          .eq('district_id', districtId);

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

  // Get geographic data by ID
  Future<GeographicModel> getGeographicById(String geographicId) async {
    try {
      final response =
          await _supabase
              .from('geographics')
              .select('*, districts(*)')
              .eq('id', geographicId)
              .single();

      return GeographicModel.fromJson(response);
    } catch (e) {
      _log.e('Error fetching geographic data $geographicId: $e');
      throw Exception('Failed to load geographic details: $e');
    }
  }

  // Get geographic data by type
  Future<List<GeographicModel>> getGeographicsByType(String type) async {
    try {
      final response = await _supabase
          .from('geographics')
          .select('*, districts(*)')
          .eq('type', type);

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

  // Get geographic data for a specific year
  Future<List<GeographicModel>> getGeographicsForYear(int year) async {
    try {
      final response = await _supabase
          .from('geographics')
          .select('*, districts(*)')
          .eq('year', year);

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

  // Add or update geographic data
  Future<GeographicModel> upsertGeographic({
    String? id,
    required String districtId,
    required double latitude,
    required double longitude,
    String? description,
    String? type,
    String? address,
    double? landArea,
    int? year,
  }) async {
    try {
      final data = {
        if (id != null) 'id': id,
        'district_id': districtId,
        'latitude': latitude,
        'longitude': longitude,
        'description': description,
        'type': type,
        'address': address,
        'land_area': landArea,
        'year': year,
      };

      final response =
          await _supabase
              .from('geographics')
              .upsert(data)
              .select('*, districts(*)')
              .single();

      return GeographicModel.fromJson(response);
    } catch (e) {
      _log.e('Error saving geographic data: $e');
      throw Exception('Failed to save geographic data: $e');
    }
  }
}
