import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/features/todo_section/models/resp_models/ancillary_order_list_response_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/models/resp_models/ancillary_order_procedures_detail_response_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/todo_section_repo.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

class TodoSectionViewModel extends ChangeNotifier {
  TodoSectionRepo todoSectionRepo;
  ErrorHandlerService errorHandlerService;

  TodoSectionViewModel({required this.todoSectionRepo, required this.errorHandlerService});

  String? notificationsCount = "0";

  initializeTodoSectionViewModel() async {
    if (isAncillaryOrdersNeedReloading) {
      patientAncillaryOrdersList.clear();
      isAncillaryOrdersLoading = true;
      isAncillaryDetailsProceduresLoading = true;
      notificationsCount = "0";
      getPatientOnlineAncillaryOrderList();
    }
    getPatientDashboard();
  }

  bool isAncillaryOrdersLoading = false;
  bool isAncillaryDetailsProceduresLoading = false;
  bool isProcessingPayment = false;
  bool isAncillaryOrdersNeedReloading = true;
  List<AncillaryOrderItem> patientAncillaryOrdersList = [];
  List<AncillaryOrderProcedureItem> patientAncillaryOrderProceduresList = [];

  void setProcessingPayment(bool value) {
    isProcessingPayment = value;
    notifyListeners();
  }

  void setIsAncillaryOrdersNeedReloading(bool value) {
    isAncillaryOrdersNeedReloading = value;
    notifyListeners();
  }

  Future<void> getPatientDashboard({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await todoSectionRepo.getPatientDashboard();

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
      },
      (apiResponse) {
        // if (apiResponse.messageStatus == 2) {
        // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        // } else if (apiResponse.messageStatus == 1) {
        if (apiResponse['List_PatientDashboard'] != null && apiResponse['List_PatientDashboard'] is List && (apiResponse['List_PatientDashboard'] as List).isNotEmpty) {
          notificationsCount =
              apiResponse['List_PatientDashboard'][0]['UnreadPatientNotificationCount'] > 99 ? '99+' : apiResponse['List_PatientDashboard'][0]['UnreadPatientNotificationCount'].toString();
        } else {
          notificationsCount = "0";
        }
        notifyListeners();
        if (onSuccess != null) {
          onSuccess(apiResponse);
        }
        // }
      },
    );
  }

  Future<void> getPatientOnlineAncillaryOrderList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    if (!isAncillaryOrdersNeedReloading) {
      return;
    }

    patientAncillaryOrdersList.clear();
    isAncillaryOrdersLoading = true;
    notifyListeners();

    final result = await todoSectionRepo.getOnlineAncillaryOrderList();

    result.fold(
      (failure) async {
        isAncillaryOrdersLoading = false;
        await errorHandlerService.handleError(failure: failure);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientAncillaryOrdersList = apiResponse.data!;
          isAncillaryOrdersLoading = false;
          isAncillaryOrdersNeedReloading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientOnlineAncillaryOrderDetailsProceduresList({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
    required int appointmentNoVida,
    required int orderNo,
    required int projectID,
  }) async {
    isAncillaryDetailsProceduresLoading = true;
    notifyListeners();

    final result = await todoSectionRepo.getOnlineAncillaryOrderDetailsProceduresList(
      appointmentNoVida: appointmentNoVida,
      orderNo: orderNo,
      projectID: projectID,
    );

    result.fold(
      (failure) async {
        isAncillaryDetailsProceduresLoading = false;
        await errorHandlerService.handleError(failure: failure);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientAncillaryOrderProceduresList = apiResponse.data!;
          isAncillaryDetailsProceduresLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> checkPaymentStatus({
    required String transID,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await todoSectionRepo.checkPaymentStatus(transID: transID);

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  Future<void> createAdvancePayment({
    required int projectID,
    required num paymentAmount,
    required String paymentReference,
    required String paymentMethodName,
    required int patientTypeID,
    required String patientName,
    required int patientID,
    required String setupID,
    required bool isAncillaryOrder,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await todoSectionRepo.createAdvancePayment(
      projectID: projectID,
      paymentAmount: paymentAmount,
      paymentReference: paymentReference,
      paymentMethodName: paymentMethodName,
      patientTypeID: patientTypeID,
      patientName: patientName,
      patientID: patientID,
      setupID: setupID,
      isAncillaryOrder: isAncillaryOrder,
    );

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  Future<void> addAdvancedNumberRequest({
    required String advanceNumber,
    required String paymentReference,
    required int appointmentID,
    required int patientID,
    required int patientTypeID,
    required int patientOutSA,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await todoSectionRepo.addAdvancedNumberRequest(
      advanceNumber: advanceNumber,
      paymentReference: paymentReference,
      appointmentID: appointmentID,
      patientID: patientID,
      patientTypeID: patientTypeID,
      patientOutSA: patientOutSA,
    );

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  Future<void> autoGenerateAncillaryOrdersInvoice({
    required int orderNo,
    required int projectID,
    required int appointmentNo,
    required List<dynamic> selectedProcedures,
    required int languageID,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await todoSectionRepo.autoGenerateAncillaryOrdersInvoice(
      orderNo: orderNo,
      projectID: projectID,
      appointmentNo: appointmentNo,
      selectedProcedures: selectedProcedures,
      languageID: languageID,
    );

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  Future<void> applePayInsertRequest({
    required dynamic applePayInsertRequest,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await todoSectionRepo.applePayInsertRequest(applePayInsertRequest: applePayInsertRequest);

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }
}
