import 'package:get/get.dart';

import '../../../core/config/server_response.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/BeneficiaryAccountModel.dart';


class BeneficiaryManagementController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  String className = "";
  var hasUpdated = false.obs;

  List<BeneficiaryAccountModel> allBeneficiary = <BeneficiaryAccountModel>[];
  RxList<BeneficiaryAccountModel> filteredBeneficiaries = <BeneficiaryAccountModel>[].obs;

  /// Fetch All Beneficiary Function
  Future<void> fetchAllBeneficiary(String porOrgacode, String email) async {
    try {
      ServerResponse response = await repository.fetchAllBeneficiary(porOrgacode, email);
      if (response.isError) {
        Toasty.error(response.errorMsg);
        return;
      }
      // Assuming the response contains a list of beneficiary account data
      List<dynamic> data = response.response;
      if (data != null) {
        List<BeneficiaryAccountModel> beneficiaryList = data.map((item) {
          return BeneficiaryAccountModel.fromMap(item);
        }).toList();

        // Update the RxList with the fetched data
        allBeneficiary.assignAll(beneficiaryList);
        filteredBeneficiaries.assignAll(beneficiaryList);
      }
    } catch (e) {
      Toasty.error('An error occurred while fetching beneficiary accounts.');
    }
  }

  /// Delete Beneficiary Function
  Future<void> deleteSingleBeneficiary(String mbmBkmsnumberRef, String email, String porOrgacode) async {
    ServerResponse response = await repository.deleteBeneficiary(mbmBkmsnumberRef, email, porOrgacode);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    Toasty.success('Your Beneficiary account Delete successfully.');
    fetchBeneficiaries();
  }

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

  void fetchBeneficiaries() async {
    await fetchAllBeneficiary(SessionCache.instance.userInfo.porOrgacode, SessionCache.instance.userInfo.cmpUserId);
    dp("All Beneficiary List======== ", allBeneficiary.toString());
  }

  void filterBeneficiaries(String searchText) {
    if (searchText.isEmpty) {
      filteredBeneficiaries.assignAll(allBeneficiary);
    } else {
      filteredBeneficiaries.assignAll(allBeneficiary.where((beneficiary) {
        return beneficiary.refNickName.toLowerCase().contains(searchText.toLowerCase()) || beneficiary.mbmBkmstitleRef.toLowerCase().contains(searchText.toLowerCase()) || beneficiary.mbmBkmsnumberRef.toLowerCase().contains(searchText.toLowerCase());
      }).toList());
    }
  }
}
