import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../domain/provider/tenant/get_tenant_pro.dart';
import '../../modules/orders/getcustomerorders.dart';
import '../../modules/tenant/get_tenant.dart';

class OrderedTenantController extends GetxController {
  final CustomerTenantsProvider provider = CustomerTenantsProvider();

  var isLoading = false.obs;
  var orders = <Order>[].obs; // ✅ Use Order, not OrderDatum

  int pageNo = 1;
  int pageSize = 10;
  bool allLoaded = false;

  @override
  void onInit() {
    super.onInit();
    loadOrders();
  }

  /// Reload orders from page 1
  Future<void> refreshOrders() async {
    allLoaded = false;
    pageNo = 1;
    orders.clear();
    await loadOrders();
  }

  /// Load orders with pagination and duplicate prevention
  Future<void> loadOrders() async {
    if (allLoaded || isLoading.value) return;

    try {
      isLoading.value = true;

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

      if (customerId == null) {
        Get.snackbar('Error', 'No customer ID found. Please log in.');
        return;
      }

      final response = await provider.getCustomerOrderss(
        customerId,
        pageNo: pageNo,
        pageSize: pageSize,
      );

      print('Requested page: $pageNo, pageSize: $pageSize');

      if (response == null) {
        print("⚠️ API returned null response");
        return;
      }

      // ✅ Use response.orders (not response.data)
      final fetchedOrders = response.orders;

      if (fetchedOrders.isEmpty) {
        allLoaded = true;
        print("✅ All orders loaded.");
        return;
      }

      // ✅ Deduplicate by orderheaderid
      final newOrders = fetchedOrders.where((newOrder) =>
      !orders.any((existing) =>
      existing.orderheaderid == newOrder.orderheaderid)).toList();

      if (newOrders.isNotEmpty) {
        orders.addAll(newOrders);
        pageNo++;
        print("✅ Orders loaded: ${orders.length}");
      } else {
        allLoaded = true; // All fetched orders already exist locally
        print("✅ No new unique orders. Marking as all loaded.");
      }

      // ✅ If fewer items than pageSize were returned, we've reached the end
      if (fetchedOrders.length < pageSize) {
        allLoaded = true;
      }
    } catch (e) {
      print("⛔ Error in loadOrders: $e");
    } finally {
      isLoading.value = false;
    }
  }
}