import 'package:flutter/cupertino.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/cache_consts.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_repo.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/models/resp_models/get_livecare_immediate_clinics_response_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/models/resp_models/get_livecare_immediate_fees_response_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/models/resp_models/get_patient_livecare_history_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

import '../../services/navigation_service.dart';

class ImmediateLiveCareViewModel extends ChangeNotifier {
  ImmediateLiveCareViewModel({
    required this.immediateLiveCareRepo,
    required this.errorHandlerService,
    required this.navigationService,
    required this.myAppointmentsViewModel,
  });

  ImmediateLiveCareRepo immediateLiveCareRepo;
  ErrorHandlerService errorHandlerService;
  final NavigationService navigationService;
  MyAppointmentsViewModel myAppointmentsViewModel;

  List<GetLiveCareClinicListResponseModel> immediateLiveCareClinicsList = [];
  bool isImmediateLiveCareClinicsLoading = false;
  int liveCareSelectedCallType = 0; // 1- Video, 2- Audio, 3- Phone
  late GetLiveCareClinicListResponseModel immediateLiveCareSelectedClinic;
  late LiveCareImmediateAppointmentFeesList liveCareImmediateAppointmentFeesList;

  List<PatientLiveCareHistory> patientLiveCareHistoryList = [];
  bool patientHasPendingLiveCareRequest = false;

  late AppState _appState;

  initImmediateLiveCare() {
    _appState = getIt<AppState>();
    immediateLiveCareClinicsList = [];
    patientLiveCareHistoryList = [];
    isImmediateLiveCareClinicsLoading = true;
    patientHasPendingLiveCareRequest = false;
    liveCareSelectedCallType = 0; // 1- Video, 2- Audio, 3- Phone
    immediateLiveCareSelectedClinic = GetLiveCareClinicListResponseModel();
    liveCareImmediateAppointmentFeesList = LiveCareImmediateAppointmentFeesList();
  }

  setLiveCareSelectedCallType(int value) {
    liveCareSelectedCallType = value;
    notifyListeners();
  }

  setImmediateLiveCareSelectedClinic(GetLiveCareClinicListResponseModel clinic) {
    immediateLiveCareSelectedClinic = clinic;
    notifyListeners();
  }

  Future<void> getLiveCareImmediateClinicsList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    immediateLiveCareClinicsList.clear();
    isImmediateLiveCareClinicsLoading = true;
    notifyListeners();

    final result = await immediateLiveCareRepo.getLiveCareImmediateClinicsList(_appState.getAuthenticatedUser()!.age!, _appState.getAuthenticatedUser()!.gender!);

    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) {
          immediateLiveCareClinicsList = apiResponse.data!;

          immediateLiveCareClinicsList.sort((a, b) => b.isOnline!.compareTo(a.isOnline!));

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

  Future<void> getLiveCareImmediateAppointmentFees({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result =
        await immediateLiveCareRepo.getLiveCareImmediateAppointmentFees(_appState.getAuthenticatedUser()!.age!, _appState.getAuthenticatedUser()!.gender!, immediateLiveCareSelectedClinic.serviceID!);

    result.fold(
      (failure) async {
        onError!(failure.message);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          onError!(apiResponse.errorMessage ?? "Unknown error occurred");
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          liveCareImmediateAppointmentFeesList = apiResponse.data!;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> addNewCallRequestForImmediateLiveCare(String transID, {Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await immediateLiveCareRepo.addNewCallRequestForImmediateLiveCare(_appState.getAuthenticatedUser()!.age!, _appState.getAuthenticatedUser()!.gender!,
        immediateLiveCareSelectedClinic.serviceID!, transID, liveCareSelectedCallType, false, _appState.deviceToken, await Utils.getStringFromPrefs(CacheConst.voipToken));

    result.fold(
      (failure) async {
        onError!(failure.message);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          onError!(apiResponse.errorMessage ?? "Unknown error occurred");
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

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

    result.fold(
      (failure) async {
        onError!(failure.message);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          onError!(apiResponse.errorMessage ?? "Unknown error occurred");
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientLiveCareHistoryList = apiResponse.data!;
          if (patientLiveCareHistoryList.isNotEmpty) {
            if (patientLiveCareHistoryList[0].callStatus! < 4) {
              patientHasPendingLiveCareRequest = true;
            } else {
              patientHasPendingLiveCareRequest = false;
            }
          } else {
            patientHasPendingLiveCareRequest = false;
          }
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }
}
