import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../../../Data/Repository/Customers/getCustomerbytenantidrepository.dart';
import '../../../../../Helper/toast.dart';
import '../../../../../Model/Response/Customers/GetCustomerById/GetCustomerByTenantId.dart';


class TenantPickupCustomerController extends GetxController{

  final int limit = 10;
  int page = 1;
  var hasMore = true.obs;

  bool progress = true;

  RxBool shimmer = true.obs;

  var getCustomerBytenantId = <GetCustomerByTenantIdDetails>[].obs;


  TextEditingController searchController = TextEditingController();

  GetCustomersByTenantIdRepository getCustomersByTenantIdRepository = GetCustomersByTenantIdRepository();

  getCustomerByTenantId()async{
    GetCustomerByTenantId? result = await getCustomersByTenantIdRepository.getCustomerByTenantId();
    getCustomerByTenantIdResult(result!);
  }

  getTenantsByTenantId()async{
    GetCustomerByTenantId? result = await getCustomersByTenantIdRepository.getTenantsByTenantId();
    getCustomerByTenantIdResult(result!);
  }


  getCustomerByTenantIdResult(GetCustomerByTenantId data) {
    final seen = <dynamic>{};

    /// Logic to remove duplicates
    getCustomerBytenantId.value = (data.details ?? []).where((customer) {
      if (seen.contains(customer.customerid)) {
        return false; // Duplicate
      } else {
        seen.add(customer.customerid);
        return true;
      }
    }).toList();

    progress = false;
    update();
  }


  Future getSearchCustomerData(keyword) async {

    GetCustomerByTenantId? result = await getCustomersByTenantIdRepository.getCustomerKeywordByTenantId(keyword);

    if (result?.code == 200) {
      getCustomerBytenantId.clear();
      getCustomerBytenantId.addAll(result?.details??[]);
      shimmer.value = false;
      update();
      print('getSearchCustomerDatalength ${getCustomerBytenantId.length}');
      if(getCustomerBytenantId.isEmpty){
        Toast.showToast('No customer at this moment');
      }

    } else {
      // Toast.showToast(result?.message??"");
    }
  }

  Future refreshData() async {
    searchController.clear();
    page = 1;
    hasMore.value = true;
    getCustomerBytenantId.value = [];


    if(searchController.text.isEmpty){
      print("ifffffffffffffffffffffffffffffffffff");
      await getCustomerData();
    }
  }

  Future getCustomerData() async {
    GetCustomerByTenantId? result = await getCustomersByTenantIdRepository.getCustomerByPageLimitTenantId(page,limit);

    if (result?.code == 200) {
      if (result!.details!.length < limit) {
        hasMore.value = false;
      }
      // getCustomerBytenantId.clear();
      getCustomerBytenantId.addAll(result.details??[]);
      shimmer.value = false;
      page++;
      update();
    } else {
      // Toast.showToast(result?.message??"");
    }
  }




  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }
}