import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/features/services_price_list/models/resp_models/services_price_list_response_model.dart';
import 'package:hmg_patient_app_new/features/services_price_list/services_price_list_repo.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

class ServicesPriceListViewModel extends ChangeNotifier {
  bool isServicesPriceListLoading = false;

  ServicesPriceListRepo servicesPriceListRepo;
  ErrorHandlerService errorHandlerService;

  List<ServicesPriceListResponseModel> servicesPriceList = [];
  List<ServicesPriceListResponseModel> filteredServicesPriceList = [];

  String searchKey = "";

  ServicesPriceListViewModel({
    required this.servicesPriceListRepo,
    required this.errorHandlerService,
  });

  initServicesPriceListProvider() {
    servicesPriceList.clear();
    filteredServicesPriceList.clear();
    isServicesPriceListLoading = true;
    getServicesPriceList();
    notifyListeners();
  }

  setIsServicesPriceListLoading(bool val) {
    isServicesPriceListLoading = val;
    notifyListeners();
  }

  setSearchKey(String val) {
    searchKey = val;
    filterServicesList(val);
  }

  void filterServicesList(String query) {
    if (query.isEmpty) {
      filteredServicesPriceList = List.from(servicesPriceList);
    } else {
      filteredServicesPriceList = servicesPriceList.where((service) {
        final nameEN = service.nameEN?.toLowerCase() ?? '';
        final nameAR = service.nameAR?.toLowerCase() ?? '';
        final searchLower = query.toLowerCase();
        return nameEN.contains(searchLower) || nameAR.contains(searchLower);
      }).toList();
    }
    notifyListeners();
  }

  Future<void> getServicesPriceList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await servicesPriceListRepo.getServicesPriceList(
      searchKey: searchKey,
    );

    result.fold(
      (failure) async {
        isServicesPriceListLoading = false;
        notifyListeners();
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          isServicesPriceListLoading = false;
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? "Error loading services price list");
          }
        } else if (apiResponse.messageStatus == 1) {
          servicesPriceList = apiResponse.data!;
          servicesPriceList.removeWhere((element) => element.isEnabled == false);
          filteredServicesPriceList = List.from(servicesPriceList);
          isServicesPriceListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }
}
