import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/api/api_client.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

/// Progress types to request different ranges from the progress API.
enum ProgressType { today, week, month }

abstract class HealthTrackersRepo {
  // ==================== BLOOD SUGAR (DIABETIC) ====================
  /// Get blood sugar result averages (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getDiabeticResultAverage();

  /// Get blood sugar results (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getDiabeticResults();
  Future<Either<Failure, GenericApiModel<String>>> downloadBloodSugarReport();
  Future<Either<Failure, GenericApiModel<String>>> downloadWeightReport();
  Future<Either<Failure, GenericApiModel<String>>> downloadBloodPressureReport();

  /// Add new blood sugar result.
  Future<Either<Failure, GenericApiModel<dynamic>>> addDiabeticResult({
    required String bloodSugarDateChart,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
  });

  /// Update existing blood sugar result.
  Future<Either<Failure, GenericApiModel<dynamic>>> updateDiabeticResult({
    required DateTime month,
    required DateTime hour,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
    required int lineItemNo,
  });

  /// Deactivate blood sugar record.
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateDiabeticStatus({
    required int lineItemNo,
  });

  /// Send blood sugar report by email.
  Future<Either<Failure, GenericApiModel<dynamic>>> sendBloodSugarReportByEmail({
    required String email,
  });

  // ==================== BLOOD PRESSURE ====================
  /// Get blood pressure result averages (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getBloodPressureResultAverage();

  /// Get blood pressure results (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getBloodPressureResults();

  /// Add new blood pressure result.
  Future<Either<Failure, GenericApiModel<dynamic>>> addBloodPressureResult({
    required String bloodPressureDate,
    required String diastolicPressure,
    required String systolicePressure,
    required int measuredArm,
  });

  /// Update existing blood pressure result.
  Future<Either<Failure, GenericApiModel<dynamic>>> updateBloodPressureResult({
    required String bloodPressureDate,
    required String diastolicPressure,
    required String systolicePressure,
    required int measuredArm,
    required int lineItemNo,
  });

  /// Deactivate blood pressure record.
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateBloodPressureStatus({
    required int lineItemNo,
  });

  /// Send blood pressure report by email.
  Future<Either<Failure, GenericApiModel<dynamic>>> sendBloodPressureReportByEmail({
    required String email,
  });

  // ==================== WEIGHT MEASUREMENT ====================
  /// Get weight measurement result averages (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getWeightMeasurementResultAverage();

  /// Get weight measurement results (week, month, year).
  Future<Either<Failure, GenericApiModel<dynamic>>> getWeightMeasurementResults();

  /// Add new weight measurement result.
  Future<Either<Failure, GenericApiModel<dynamic>>> addWeightMeasurementResult({
    required String weightDate,
    required String weightMeasured,
    required int weightUnit,
  });

  /// Update existing weight measurement result.
  Future<Either<Failure, GenericApiModel<dynamic>>> updateWeightMeasurementResult({
    required int lineItemNo,
    required int weightUnit,
    required String weightMeasured,
    required String weightDate,
  });

  /// Deactivate weight measurement record.
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateWeightMeasurementStatus({
    required int lineItemNo,
  });

  /// Send weight report by email.
  Future<Either<Failure, GenericApiModel<dynamic>>> sendWeightReportByEmail({
    required String email,
  });
}

class HealthTrackersRepoImp implements HealthTrackersRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

  HealthTrackersRepoImp({required this.loggerService, required this.apiClient});

  // ==================== BLOOD SUGAR (DIABETIC) METHODS ====================

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getDiabeticResultAverage() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getDiabeticResultAverage,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract average lists
              extracted = {
                'monthAverageList': response['List_MonthDiabtectResultAverage'] ?? [],
                'weekAverageList': response['List_WeekDiabtectResultAverage'] ?? [],
                'yearAverageList': response['List_YearDiabtecResultAverage'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getDiabeticResults() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getDiabeticResult,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract patient result lists
              extracted = {
                'monthResultList': response['List_MonthDiabtecPatientResult'] ?? [],
                'weekResultList': response['List_WeekDiabtecPatientResult'] ?? [],
                'yearResultList': response['List_YearDiabtecPatientResult'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<String>>> downloadBloodSugarReport() async {
    try {
      GenericApiModel<String>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.averageBloodSugarReportDownload,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic pdf = response['ReportPDFContent'];

            apiResponse = GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: pdf,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }


  @override
  Future<Either<Failure, GenericApiModel<String>>> downloadWeightReport() async {
    try {
      GenericApiModel<String>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.averageWeightReportDownload,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic pdf = response['ReportPDFContent'];

            apiResponse = GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: pdf,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }
  @override
  Future<Either<Failure, GenericApiModel<String>>> downloadBloodPressureReport() async {
    try {
      GenericApiModel<String>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.averageBloodPressureReportDownload,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic pdf = response['ReportPDFContent'];

            apiResponse = GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: pdf,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> addDiabeticResult({
    required String bloodSugarDateChart,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'BloodSugerDateChart': bloodSugarDateChart,
        'BloodSugerResult': bloodSugarResult,
        'DiabtecUnit': diabeticUnit,
        'MeasuredTime': measuredTime + 1, // Add 1 as per old service
      };

      await apiClient.post(
        ApiConsts.addDiabeticResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> updateDiabeticResult({
    required DateTime month,
    required DateTime hour,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
    required int lineItemNo,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      // Format: 'YYYY-MM-DD HH:MM:SS' as per old service
      String formattedDate = '${month.year}-${month.month}-${month.day} ${hour.hour}:${hour.minute}:00';

      Map<String, dynamic> body = {
        'BloodSugerDateChart': formattedDate,
        'BloodSugerResult': bloodSugarResult,
        'DiabtecUnit': diabeticUnit,
        'MeasuredTime': measuredTime + 1, // Add 1 as per old service
        'LineItemNo': lineItemNo,
      };

      await apiClient.post(
        ApiConsts.updateDiabeticResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateDiabeticStatus({
    required int lineItemNo,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'LineItemNo': lineItemNo,
      };

      await apiClient.post(
        ApiConsts.deactivateDiabeticStatus,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> sendBloodSugarReportByEmail({
    required String email,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'To': email,
      };

      await apiClient.post(
        ApiConsts.sendAverageBloodSugarReport,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  // ==================== BLOOD PRESSURE METHODS ====================

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getBloodPressureResultAverage() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getBloodPressureResultAverage,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract all three list types
              extracted = {
                'monthList': response['List_MonthBloodPressureResultAverage'] ?? [],
                'weekList': response['List_WeekBloodPressureResultAverage'] ?? [],
                'yearList': response['List_YearBloodPressureResultAverage'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getBloodPressureResults() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getBloodPressureResult,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract all three list types
              extracted = {
                'weekList': response['List_WeekBloodPressureResult'] ?? [],
                'monthList': response['List_MonthBloodPressureResult'] ?? [],
                'yearList': response['List_YearBloodPressureResult'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> addBloodPressureResult({
    required String bloodPressureDate,
    required String diastolicPressure,
    required String systolicePressure,
    required int measuredArm,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'BloodPressureDate': bloodPressureDate,
        'DiastolicPressure': diastolicPressure,
        'SystolicePressure': systolicePressure,
        'MeasuredArm': measuredArm,
      };

      await apiClient.post(
        ApiConsts.addBloodPressureResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> updateBloodPressureResult({
    required String bloodPressureDate,
    required String diastolicPressure,
    required String systolicePressure,
    required int measuredArm,
    required int lineItemNo,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'BloodPressureDate': bloodPressureDate,
        'DiastolicPressure': diastolicPressure,
        'SystolicePressure': systolicePressure,
        'MeasuredArm': measuredArm,
        'LineItemNo': lineItemNo,
      };

      await apiClient.post(
        ApiConsts.updateBloodPressureResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateBloodPressureStatus({
    required int lineItemNo,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'LineItemNo': lineItemNo,
      };

      await apiClient.post(
        ApiConsts.deactivateBloodPressureStatus,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> sendBloodPressureReportByEmail({
    required String email,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'To': email,
      };

      await apiClient.post(
        ApiConsts.sendAverageBloodPressureReport,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  // ==================== WEIGHT MEASUREMENT METHODS ====================

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getWeightMeasurementResultAverage() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getWeightMeasurementResultAverage,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract average lists
              extracted = {
                'monthAverageList': response['List_MonthWeightMeasurementResultAverage'] ?? [],
                'weekAverageList': response['List_WeekWeightMeasurementResultAverage'] ?? [],
                'yearAverageList': response['List_YearWeightMeasurementResultAverage'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getWeightMeasurementResults() async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getWeightMeasurementResult,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            dynamic extracted;
            if (response is Map) {
              // Extract result lists
              extracted = {
                'weekResultList': response['List_WeekWeightMeasurementResult'] ?? [],
                'monthResultList': response['List_MonthWeightMeasurementResult'] ?? [],
                'yearResultList': response['List_YearWeightMeasurementResult'] ?? [],
              };
            } else {
              extracted = response;
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: extracted,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> addWeightMeasurementResult({
    required String weightDate,
    required String weightMeasured,
    required int weightUnit,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'WeightDate': weightDate,
        'WeightMeasured': weightMeasured,
        'weightUnit': weightUnit,
      };

      await apiClient.post(
        ApiConsts.addWeightMeasurementResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> updateWeightMeasurementResult({
    required int lineItemNo,
    required int weightUnit,
    required String weightMeasured,
    required String weightDate,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'LineItemNo': lineItemNo,
        'weightUnit': '$weightUnit', // Convert to string as per old service
        'WeightMeasured': weightMeasured,
        'WeightDate': weightDate,
      };

      await apiClient.post(
        ApiConsts.updateWeightMeasurementResult,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> deactivateWeightMeasurementStatus({required int lineItemNo}) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'LineItemNo': lineItemNo,
      };

      await apiClient.post(
        ApiConsts.deactivateWeightMeasurementStatus,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> sendWeightReportByEmail({
    required String email,
  }) async {
    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;

      Map<String, dynamic> body = {
        'To': email,
      };

      await apiClient.post(
        ApiConsts.sendAverageBodyWeightReport,
        body: body,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: errorMessage,
            data: response,
          );
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }
}
