import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/features/insurance/insurance_repo.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_approval_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_card_history.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_details_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_update_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/upload_insurance_card_response_model.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

class InsuranceViewModel extends ChangeNotifier {
  bool isInsuranceLoading = false;
  bool isInsuranceHistoryLoading = false;
  bool isInsuranceDetailsLoading = false;
  bool isInsuranceUpdateDetailsLoading = false;
  bool isInsuranceExpiryBannerShown = false;

  bool isInsuranceDataToBeLoaded = true;
  bool isInsuranceApprovalsLoading = false;

  bool isInsuranceExpired = false;
  bool isInsuranceActive = false;

  InsuranceRepo insuranceRepo;
  ErrorHandlerService errorHandlerService;

  List<PatientInsuranceDetailsResponseModel> patientInsuranceList = [];
  List<PatientInsuranceCardHistoryResponseModel> patientInsuranceCardHistoryList = [];
  List<InsuranceApprovalResponseModel> patientInsuranceApprovalsList = [];

  PatientInsuranceUpdateResponseModel? patientInsuranceUpdateResponseModel;

  InsuranceViewModel({required this.insuranceRepo, required this.errorHandlerService});

  initInsuranceProvider() {
    if (isInsuranceDataToBeLoaded) {
      patientInsuranceList.clear();
      isInsuranceLoading = true;
      getPatientInsuranceDetails();
    }
    patientInsuranceCardHistoryList.clear();
    isInsuranceHistoryLoading = true;
    isInsuranceDetailsLoading = true;
    isInsuranceUpdateDetailsLoading = true;
    isInsuranceApprovalsLoading = true;
    notifyListeners();
  }

  setIsInsuranceExpiryBannerShown(bool isInsuranceExpiryBannerShown) {
    this.isInsuranceExpiryBannerShown = isInsuranceExpiryBannerShown;
    notifyListeners();
  }

  setIsInsuranceHistoryLoading(bool val) {
    isInsuranceHistoryLoading = val;
    notifyListeners();
  }

  setIsInsuranceDetailsLoading(bool val) {
    isInsuranceDetailsLoading = val;
    notifyListeners();
  }

  setIsInsuranceUpdateDetailsLoading(bool val) {
    isInsuranceUpdateDetailsLoading = val;
    notifyListeners();
  }

  setIsInsuranceDataToBeLoaded(bool val) {
    isInsuranceDataToBeLoaded = val;
    notifyListeners();
  }

  setIsInsuranceApprovalsLoading(bool val) {
    isInsuranceApprovalsLoading = val;
    notifyListeners();
  }

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

    final result = await insuranceRepo.getPatientInsuranceDetails();

    result.fold(
      // (failure) async => await errorHandlerService.handleError(failure: failure),
      (failure) async {
        isInsuranceLoading = false;
        isInsuranceDataToBeLoaded = true;
        isInsuranceExpired = false;
        isInsuranceActive = false;
        isInsuranceExpiryBannerShown = false;
        notifyListeners();
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          isInsuranceDataToBeLoaded = false;
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientInsuranceList = apiResponse.data!;
          isInsuranceLoading = false;
          isInsuranceDataToBeLoaded = false;

          if (patientInsuranceList.isNotEmpty) {
            isInsuranceExpired = DateTime.now().isAfter(
              DateUtil.convertStringToDate(patientInsuranceList.first.cardValidTo),
            );
          }

          isInsuranceExpiryBannerShown = isInsuranceExpired;

          isInsuranceActive = patientInsuranceList.first.isActive ?? false;
          // isInsuranceActive = true;

          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

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

    result.fold(
      (failure) async {
        isInsuranceHistoryLoading = false;
        notifyListeners();
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientInsuranceCardHistoryList = apiResponse.data!;
          patientInsuranceCardHistoryList = patientInsuranceCardHistoryList.take(3).toList();
          isInsuranceHistoryLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientInsuranceDetailsForUpdate(String patientID, String identificationNo, {Function(dynamic)? onSuccess, Function(String)? onError}) async {
    patientInsuranceUpdateResponseModel = null;
    notifyListeners();

    final result = await insuranceRepo.getPatientInsuranceDetailsForUpdate(patientId: patientID, identificationNo: identificationNo);

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

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

    result.fold(
      (failure) async {
        isInsuranceApprovalsLoading = false;
        notifyListeners();
      },
      (apiResponse) {
        patientInsuranceApprovalsList =[];
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientInsuranceApprovalsList = apiResponse.data!;
          isInsuranceApprovalsLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> updatePatientInsuranceCard({
    required int patientID,
    required int patientType,
    required String mobileNo,
    required String patientIdentificationID,
    required String insuranceCardImage,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result = await insuranceRepo.updatePatientInsuranceCard(
      patientID: patientID,
      patientType: patientType,
      mobileNo: mobileNo,
      patientIdentificationID: patientIdentificationID,
      insuranceCardImage: insuranceCardImage,
    );

    result.fold(
      (failure) async {
        notifyListeners();
        if (onError != null) {
          onError(failure.message.toString());
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? "Error updating insurance card");
          }
        } else if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }
}
