import 'dart:io';

import 'package:hmg_patient_app_new/core/exceptions/api_exception.dart';
import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/core/utils/loading_utils.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';

abstract class ErrorHandlerService {
  Future<void> handleError({required Failure failure, Function() onOkPressed});
}

class ErrorHandlerServiceImp implements ErrorHandlerService {
  final DialogService dialogService;
  final LoggerService loggerService;
  final NavigationService navigationService;

  ErrorHandlerServiceImp({
    required this.dialogService,
    required this.loggerService,
    required this.navigationService,
  });

  @override
  Future<void> handleError({required Failure failure, Function()? onOkPressed}) async {
    if (failure is APIException) {
      loggerService.errorLogs("API Exception: ${failure.message}");
    } else if (failure is ServerFailure) {
      loggerService.errorLogs("Server Failure: ${failure.message}");
      await _showDialog(failure);
    } else if (failure is DataParsingFailure) {
      loggerService.errorLogs("Data Parsing Failure: ${failure.message}");
      await _showDialog(failure, title: "Data Error");
    } else if (failure is StatusCodeFailure) {
      loggerService.errorLogs("StatusCode Failure: ${failure.message}");
      await _showDialog(failure, title: "Status Code Failure Error");
    } else if (failure is HttpException) {
      loggerService.errorLogs("Http Exception: ${failure.message}");
      await _showDialog(failure, title: "Network Error");
    } else if (failure is UnknownFailure) {
      loggerService.errorLogs("Unknown Failure: ${failure.message}");
      await _showDialog(failure, title: "Unknown Error");
    } else if (failure is InvalidCredentials) {
      loggerService.errorLogs("Invalid Credentials : ${failure.message}");
      await _showDialog(failure, title: "Unknown Error");
    } else {
      loggerService.errorLogs("Unhandled failure type: $failure");

      await _showDialog(failure, title: "Error");
    }
  }

  Future<void> _showDialog(Failure failure, {String title = "Error", Function()? onOkPressed}) async {
    if (LoadingUtils.isLoading) {
      LoadingUtils.hideFullScreenLoader();
    }
    await dialogService.showErrorBottomSheet(message: failure.message, onOkPressed: onOkPressed);
  }
}
