import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../domain/provider/tenant/get_tenant_pro.dart';
import '../../modules/tenant/get_tenant.dart';

class TenantController extends GetxController {
  final CustomerTenantsProvider provider = CustomerTenantsProvider();
  var selectedCategoryId = 0.obs;
  var isLoading = false.obs;
  var customerFirstName = ''.obs;
  var profileImage = ''.obs;
  var tenants = <Tenant>[].obs;
  var searchtenants = <Tenant>[].obs;
  var isConnected = true.obs;

  @override
  void onInit() {
    super.onInit();
    loadTenants();
    loadTenants2(categoryId: 0);
    // Listen for connectivity changes
    // Listen for connectivity changes
    Connectivity().onConnectivityChanged.listen((status) {
      bool connected = (status != ConnectivityResult.none);

      // If we were offline and now online → reload tenants
      if (!isConnected.value && connected) {
        loadTenants();
      }

      isConnected.value = connected;
    });
  }

  Future<bool> hasInternet() async {
    try {
      final response = await http.get(Uri.parse('https://www.google.com'))
          .timeout(const Duration(seconds: 5));

      if (response.statusCode == 200) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<void> loadTenants({int? categoryId}) async {
    isLoading.value = true;

    bool connected = await hasInternet();
    if (!connected) {
      isLoading.value = false;
      isConnected.value = false;
      return;
    } else {
      isConnected.value = true;
    }

    try {
      final prefs = await SharedPreferences.getInstance();
      final customerId = prefs.getInt('customerId');

      if (customerId == null) {
        print("⚠️ No customer id found");
        return;
      }

      // 🔥 Use selectedCategoryId if passed
      final response = await provider.getCustomerTenants(
        customerId,
        categoryId ?? selectedCategoryId.value,
      );

      if (response != null && response.status == true && response.details != null) {
        tenants.value = response.details!;
        print("✅ Tenants loaded: ${tenants.length}");
      } else {
        print("⚠️ Failed: ${response?.message}");
      }
    } catch (e) {
      print("⛔ Error: $e");
    } finally {
      isLoading.value = false;
    }
  }


  Future<void> loadTenants2({int? categoryId}) async {
    isLoading.value = true;

    bool connected = await hasInternet();
    if (!connected) {
      isLoading.value = false;
      isConnected.value = false;
      return;
    } else {
      isConnected.value = true;
    }

    try {
      final prefs = await SharedPreferences.getInstance();
      final customerId = prefs.getInt('customerId');

      if (customerId == null) {
        print("⚠️ No customer id found");
        return;
      }

      // 🔥 Use selectedCategoryId if passed
      final response = await provider.getCustomerTenants(
        customerId,
        categoryId ?? 0,
      );

      if (response != null && response.status == true && response.details != null) {
        searchtenants.value = response.details!;
        print("✅ Tenants loaded: ${searchtenants.length}");
      } else {
        print("⚠️ Failed: ${response?.message}");
      }
    } catch (e) {
      print("⛔ Error: $e");
    } finally {
      isLoading.value = false;
    }
  }


}
