import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_repo.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/blood_pressure_result.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/month_blood_pressure_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/week_blood_pressure_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/year_blood_pressure_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/diabetic_patient_result.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/month_diabetic_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/weight/month_weight_measurement_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/weight/week_weight_measurement_result_average.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/weight/weight_measurement_result.dart';
import 'package:hmg_patient_app_new/features/health_trackers/models/weight/year_weight_measurement_result_average.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';

class HealthTrackersViewModel extends ChangeNotifier {
  HealthTrackersRepo healthTrackersRepo;
  ErrorHandlerService errorHandlerService;

  HealthTrackersViewModel({required this.healthTrackersRepo, required this.errorHandlerService});

  // ==================== STATE MANAGEMENT ====================
  bool isLoading = false;
  String? _errorMessage;

  String? get errorMessage => _errorMessage;

  // ==================== FORM ERROR TRACKING ====================
  // Individual field errors
  String? _bloodSugarError;
  String? _bloodSugarMeasureTimeError;
  String? _dateError;
  String? _timeError;
  String? _weightError;
  String? _systolicError;
  String? _diastolicError;
  String? _measuredArmError;

  // Getters for field errors
  String? get bloodSugarError => _bloodSugarError;
  String? get bloodSugarMeasureTimeError => _bloodSugarMeasureTimeError;
  String? get dateError => _dateError;
  String? get timeError => _timeError;
  String? get weightError => _weightError;
  String? get systolicError => _systolicError;
  String? get diastolicError => _diastolicError;
  String? get measuredArmError => _measuredArmError;

  // Check if blood sugar form has any errors (for container border)
  bool get hasBloodSugarFormError =>
      _bloodSugarError != null ||
      _bloodSugarMeasureTimeError != null ||
      _dateError != null ||
      _timeError != null;

  // Check if weight form has any errors (for container border)
  bool get hasWeightFormError =>
      _weightError != null ||
      _dateError != null ||
      _timeError != null;

  // Check if blood pressure form has any errors (for container border)
  bool get hasBloodPressureFormError =>
      _systolicError != null ||
      _diastolicError != null ||
      _measuredArmError != null ||
      _dateError != null ||
      _timeError != null;

  // Clear all field errors
  void clearAllFieldErrors() {
    _bloodSugarError = null;
    _bloodSugarMeasureTimeError = null;
    _dateError = null;
    _timeError = null;
    _weightError = null;
    _systolicError = null;
    _diastolicError = null;
    _measuredArmError = null;
    notifyListeners();
  }

  // Clear individual field errors
  void clearBloodSugarError() {
    _bloodSugarError = null;
    notifyListeners();
  }

  void clearBloodSugarMeasureTimeError() {
    _bloodSugarMeasureTimeError = null;
    notifyListeners();
  }

  void clearDateError() {
    _dateError = null;
    notifyListeners();
  }

  void clearTimeError() {
    _timeError = null;
    notifyListeners();
  }

  void clearWeightError() {
    _weightError = null;
    notifyListeners();
  }

  void clearSystolicError() {
    _systolicError = null;
    notifyListeners();
  }

  void clearDiastolicError() {
    _diastolicError = null;
    notifyListeners();
  }

  void clearMeasuredArmError() {
    _measuredArmError = null;
    notifyListeners();
  }

  final List<String> durationFiltersEn = ["Week", "Month", "Year"];
  final List<String> durationFiltersAr = ["أسبوع", "شهر", "سنة"];

  List<String> get durationFilters => getIt.get<AppState>().isArabic() ? durationFiltersAr : durationFiltersEn;

  String _selectedDuration = "Week";
  bool _isGraphView = true;

  String get selectedDurationFilter => _selectedDuration;

  // Get the localized display value for the selected duration
  String get selectedDurationFilterDisplay {
    final index = durationFiltersEn.indexOf(_selectedDuration);
    if (index >= 0) {
      return getIt.get<AppState>().isArabic() ? durationFiltersAr[index] : durationFiltersEn[index];
    }
    return _selectedDuration;
  }

  bool get isGraphView => _isGraphView;

  final List<String> bloodSugarUnit = ['mg/dlt', 'mol/L'];

  String _selectedBloodSugarUnit = 'mg/dlt';

  String get selectedBloodSugarUnit => _selectedBloodSugarUnit;

  String _selectedBloodSugarMeasureTime = '';

  String get selectedBloodSugarMeasureTime => _selectedBloodSugarMeasureTime;

  final List<String> bloodSugarMeasureTimeEnList = [
    'Before Breakfast',
    'After Breakfast',
    'Before Lunch',
    'After Lunch',
    'Before Dinner',
    'After Dinner',
    'Before Sleep',
    'After Sleep',
    'Fasting',
    'Other',
  ];
  final List<String> bloodSugarMeasureTimeArList = [
    "قبل الإفطار",
    "بعد الإفطار",
    "قبل الغداء",
    "بعد الغداء",
    "قبل العشاء",
    "بعد العشاء",
    "قبل النوم",
    "بعد النوم",
    "صائم",
    "آخر",
  ];

  List<String> getBloodSugarTimeList(){
    return getIt.get<AppState>().isArabic()?bloodSugarMeasureTimeArList:bloodSugarMeasureTimeEnList;
  }

  // Setters with notification
  void setBloodSugarMeasureTime(String duration) async {
    _selectedBloodSugarMeasureTime = duration;
    notifyListeners();
  }

  // Setters with notification
  void setFilterDuration(String duration) async {
    // Map Arabic values to English keys
    if (getIt.get<AppState>().isArabic()) {
      final index = durationFiltersAr.indexOf(duration);
      if (index >= 0 && index < durationFiltersEn.length) {
        _selectedDuration = durationFiltersEn[index];
      }
    } else {
      _selectedDuration = duration;
    }
    notifyListeners();
  }

  // Setters with notification
  void setGraphView(bool value) {
    _isGraphView = value;
    notifyListeners();
  }

  void setBloodSugarUnit(String unit) {
    _selectedBloodSugarUnit = unit;
    notifyListeners();
  }

  // ==================== WEIGHT FORM FIELDS ====================
  final List<String> weightUnits = ['kg', 'lb'];
  final List<String> weightUnitsEn = ['kg', 'lb'];
  final List<String> weightUnitsAr = ['كجم', 'رطل'];

  String _selectedWeightUnit = 'kg';

  String get selectedWeightUnit => _selectedWeightUnit;

  List<String> getWeightUnitsList() {
    return getIt.get<AppState>().isArabic() ? weightUnitsAr : weightUnitsEn;
  }

  void setWeightUnit(String unit) {
    // Map Arabic values to English keys
    if (getIt.get<AppState>().isArabic()) {
      final index = weightUnitsAr.indexOf(unit);
      if (index >= 0 && index < weightUnitsEn.length) {
        _selectedWeightUnit = weightUnitsEn[index];
      }
    } else {
      _selectedWeightUnit = unit;
    }
    notifyListeners();
  }

  // Get the localized display value for the selected weight unit
  String get selectedWeightUnitDisplay {
    final index = weightUnitsEn.indexOf(_selectedWeightUnit);
    if (index >= 0) {
      return getIt.get<AppState>().isArabic() ? weightUnitsAr[index] : weightUnitsEn[index];
    }
    return _selectedWeightUnit;
  }

  // ==================== BLOOD PRESSURE FORM FIELDS ====================
  final List<String> measuredArmListEn = ['Left Arm', 'Right Arm'];
  final List<String> measuredArmListAr = ['الذراع الأيسر', 'الذراع الأيمن'];

  String _selectedMeasuredArm = '';

  String get selectedMeasuredArm => _selectedMeasuredArm;

  List<String> getMeasuredArmList() {
    return getIt.get<AppState>().isArabic() ? measuredArmListAr : measuredArmListEn;
  }

  void setMeasuredArm(String arm) {
    // Map Arabic values to English keys
    if (getIt.get<AppState>().isArabic()) {
      final index = measuredArmListAr.indexOf(arm);
      if (index >= 0 && index < measuredArmListEn.length) {
        _selectedMeasuredArm = measuredArmListEn[index];
      }
    } else {
      _selectedMeasuredArm = arm;
    }
    notifyListeners();
  }

  // Get the localized display value for the selected measured arm
  String get selectedMeasuredArmDisplay {
    final index = measuredArmListEn.indexOf(_selectedMeasuredArm);
    if (index >= 0) {
      return getIt.get<AppState>().isArabic() ? measuredArmListAr[index] : measuredArmListEn[index];
    }
    return _selectedMeasuredArm;
  }

  // Text Controllers
  TextEditingController weightController = TextEditingController();
  TextEditingController bloodSugarController = TextEditingController();
  TextEditingController systolicController = TextEditingController();
  TextEditingController diastolicController = TextEditingController();

  // Get current progress list based on selected duration
  // dynamic get currentProgressData {
  //   switch (_selectedDuration) {
  //     case 'Daily':
  //       return _todayProgressList;
  //     case 'Weekly':
  //       return _weekProgressList;
  //     case 'Monthly':
  //       return _monthProgressList;
  //     default:
  //       return _todayProgressList;
  //   }
  // }

  // ==================== WEIGHT TRACKING DATA ====================
  final List<MonthWeightMeasurementResultAverage> _monthWeightMeasurementResultAverage = [];
  final List<WeekWeightMeasurementResultAverage> _weekWeightMeasurementResultAverage = [];
  final List<YearWeightMeasurementResultAverage> _yearWeightMeasurementResultAverage = [];

  final List<WeightMeasurementResult> _monthWeightMeasurementResult = [];
  final List<WeightMeasurementResult> _weekWeightMeasurementResult = [];
  final List<WeightMeasurementResult> _yearWeightMeasurementResult = [];

  // Getters for weight data
  List<MonthWeightMeasurementResultAverage> get monthWeightMeasurementResultAverage => _monthWeightMeasurementResultAverage;

  List<WeekWeightMeasurementResultAverage> get weekWeightMeasurementResultAverage => _weekWeightMeasurementResultAverage;

  List<YearWeightMeasurementResultAverage> get yearWeightMeasurementResultAverage => _yearWeightMeasurementResultAverage;

  List<WeightMeasurementResult> get monthWeightMeasurementResult => _monthWeightMeasurementResult;

  List<WeightMeasurementResult> get weekWeightMeasurementResult => _weekWeightMeasurementResult;

  List<WeightMeasurementResult> get yearWeightMeasurementResult => _yearWeightMeasurementResult;

  // ==================== BLOOD PRESSURE TRACKING DATA ====================
  final List<MonthBloodPressureResultAverage> _monthBloodPressureResultAverage = [];
  final List<WeekBloodPressureResultAverage> _weekBloodPressureResultAverage = [];
  final List<YearBloodPressureResultAverage> _yearBloodPressureResultAverage = [];

  final List<BloodPressureResult> _monthBloodPressureResult = [];
  final List<BloodPressureResult> _weekBloodPressureResult = [];
  final List<BloodPressureResult> _yearBloodPressureResult = [];

  // Getters for blood pressure data
  List<MonthBloodPressureResultAverage> get monthBloodPressureResultAverage => _monthBloodPressureResultAverage;

  List<WeekBloodPressureResultAverage> get weekBloodPressureResultAverage => _weekBloodPressureResultAverage;

  List<YearBloodPressureResultAverage> get yearBloodPressureResultAverage => _yearBloodPressureResultAverage;

  List<BloodPressureResult> get monthBloodPressureResult => _monthBloodPressureResult;

  List<BloodPressureResult> get weekBloodPressureResult => _weekBloodPressureResult;

  List<BloodPressureResult> get yearBloodPressureResult => _yearBloodPressureResult;

  // ==================== BLOOD SUGAR (DIABETIC) TRACKING DATA ====================
  final List<MonthDiabeticResultAverage> _monthDiabeticResultAverage = [];
  final List<WeekDiabeticResultAverage> _weekDiabeticResultAverage = [];
  final List<YearDiabeticResultAverage> _yearDiabeticResultAverage = [];

  final List<DiabeticPatientResult> _monthDiabeticPatientResult = [];
  final List<DiabeticPatientResult> _weekDiabeticPatientResult = [];
  final List<DiabeticPatientResult> _yearDiabeticPatientResult = [];

  // Getters for blood sugar data
  List<MonthDiabeticResultAverage> get monthDiabeticResultAverage => _monthDiabeticResultAverage;

  List<WeekDiabeticResultAverage> get weekDiabeticResultAverage => _weekDiabeticResultAverage;

  List<YearDiabeticResultAverage> get yearDiabeticResultAverage => _yearDiabeticResultAverage;

  List<DiabeticPatientResult> get monthDiabeticPatientResult => _monthDiabeticPatientResult;

  List<DiabeticPatientResult> get weekDiabeticPatientResult => _weekDiabeticPatientResult;

  List<DiabeticPatientResult> get yearDiabeticPatientResult => _yearDiabeticPatientResult;

  // ==================== WEIGHT TRACKING METHODS ====================

  /// Fetch weight averages and results
  Future<void> getWeight() async {
    isLoading = true;
    notifyListeners();

    try {
      // Fetch weight averages
      final averageResult = await healthTrackersRepo.getWeightMeasurementResultAverage();

      averageResult.fold(
        // (failure) => errorHandlerService.handleError(failure: failure),
        (failure) => {},
        (apiModel) {
          final data = apiModel.data;
          if (data is Map) {
            // Clear existing data
            _monthWeightMeasurementResultAverage.clear();
            _weekWeightMeasurementResultAverage.clear();
            _yearWeightMeasurementResultAverage.clear();

            // Parse month averages
            if (data['monthAverageList'] != null) {
              for (var item in (data['monthAverageList'] as List)) {
                _monthWeightMeasurementResultAverage.add(
                  MonthWeightMeasurementResultAverage.fromJson(item),
                );
              }
            }

            // Parse week averages
            if (data['weekAverageList'] != null) {
              for (var item in (data['weekAverageList'] as List)) {
                _weekWeightMeasurementResultAverage.add(
                  WeekWeightMeasurementResultAverage.fromJson(item),
                );
              }
            }

            // Parse year averages
            if (data['yearAverageList'] != null) {
              for (var item in (data['yearAverageList'] as List)) {
                _yearWeightMeasurementResultAverage.add(
                  YearWeightMeasurementResultAverage.fromJson(item),
                );
              }
            }
          }
        },
      );

      // Fetch weight results
      final resultsResponse = await healthTrackersRepo.getWeightMeasurementResults();

      resultsResponse.fold(
        // (failure) => errorHandlerService.handleError(failure: failure),
        (failure) => {},
        (apiModel) {
          final data = apiModel.data;
          if (data is Map) {
            // Clear existing data
            _monthWeightMeasurementResult.clear();
            _weekWeightMeasurementResult.clear();
            _yearWeightMeasurementResult.clear();

            // Parse week results
            if (data['weekResultList'] != null) {
              for (var item in (data['weekResultList'] as List)) {
                _weekWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item));
              }
            }

            // Parse month results
            if (data['monthResultList'] != null) {
              for (var item in (data['monthResultList'] as List)) {
                _monthWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item));
              }
            }

            // Parse year results
            if (data['yearResultList'] != null) {
              for (var item in (data['yearResultList'] as List)) {
                _yearWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item));
              }
            }
          }
        },
      );
    } catch (e) {
      log('Error in getWeight: $e');
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  /// Add new weight result
  Future<bool> addWeightResult({
    required String weightDate,
    required String weightMeasured,
    required int weightUnit,
  }) async {
    try {
      final result = await healthTrackersRepo.addWeightMeasurementResult(
        weightDate: weightDate,
        weightMeasured: weightMeasured,
        weightUnit: weightUnit,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful add
          await getWeight();
        },
      );

      return success;
    } catch (e) {
      log('Error in addWeightResult: $e');
      return false;
    }
  }

  /// Update existing weight result
  Future<bool> updateWeightResult({
    required int lineItemNo,
    required int weightUnit,
    required String weightMeasured,
    required String weightDate,
  }) async {
    try {
      final result = await healthTrackersRepo.updateWeightMeasurementResult(
        lineItemNo: lineItemNo,
        weightUnit: weightUnit,
        weightMeasured: weightMeasured,
        weightDate: weightDate,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful update
          await getWeight();
        },
      );

      return success;
    } catch (e) {
      log('Error in updateWeightResult: $e');
      return false;
    }
  }

  /// Delete weight result
  Future<bool> deleteWeightResult({
    required int lineItemNo,
  }) async {
    try {
      final result = await healthTrackersRepo.deactivateWeightMeasurementStatus(
        lineItemNo: lineItemNo,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful delete
          await getWeight();
        },
      );

      return success;
    } catch (e) {
      return false;
    }
  }

  /// Send weight report by email
  Future<bool> sendWeightReportByEmail({
    required String email,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    try {
      final result = await healthTrackersRepo.sendWeightReportByEmail(
        email: email,
      );

      bool success = false;

      result.fold(
        (failure) {
          errorHandlerService.handleError(failure: failure);
          if (onFailure != null) onFailure("Failed to send report by email");
        },
        (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess();
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendWeightReportByEmail: $e');

      if (onFailure != null) onFailure("An error occurred");
      return false;
    }
  }


  Future<bool> downloadBloodSugerReport({
    Function(String)? onSuccess,
  }) async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingReport.tr());
    try {
      final result = await healthTrackersRepo.downloadBloodSugarReport();
      LoaderBottomSheet.hideLoader();
      bool success = false;

      result.fold(
        (failure) {
          errorHandlerService.handleError(failure: failure);
        },
        (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess(apiModel.data??"");
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendWeightReportByEmail: $e');
      return false;
    }
  }

  Future<bool> downloadBloodPressureReport({
    Function(String)? onSuccess,
  }) async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingReport.tr());
    try {
      final result = await healthTrackersRepo.downloadBloodPressureReport();
      LoaderBottomSheet.hideLoader();
      bool success = false;

      result.fold(
        (failure) {
          errorHandlerService.handleError(failure: failure);
        },
        (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess(apiModel.data??"");
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendWeightReportByEmail: $e');
      return false;
    }
  }
  Future<bool> downloadWeightReport({
    Function(String)? onSuccess,
  }) async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingReport.tr());
    try {
      final result = await healthTrackersRepo.downloadWeightReport();
      LoaderBottomSheet.hideLoader();
      bool success = false;

      result.fold(
            (failure) {
          errorHandlerService.handleError(failure: failure);
        },
            (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess(apiModel.data??"");
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendWeightReportByEmail: $e');
      return false;
    }
  }


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

  /// Fetch blood pressure averages and results
  Future<void> getBloodPressure() async {
    isLoading = true;
    notifyListeners();

    try {
      // Fetch blood pressure averages
      final averageResult = await healthTrackersRepo.getBloodPressureResultAverage();

      averageResult.fold(
        // (failure) => errorHandlerService.handleError(failure: failure),
        (failure) => {},
        (apiModel) {
          final data = apiModel.data;

          if (data is Map) {
            // Clear existing data
            _monthBloodPressureResultAverage.clear();
            _weekBloodPressureResultAverage.clear();
            _yearBloodPressureResultAverage.clear();

            // Parse month averages
            if (data['monthList'] != null) {
              for (var item in (data['monthList'] as List)) {
                _monthBloodPressureResultAverage.add(
                  MonthBloodPressureResultAverage.fromJson(item),
                );
              }
            }

            // Parse week averages
            if (data['weekList'] != null) {
              for (var item in (data['weekList'] as List)) {
                _weekBloodPressureResultAverage.add(
                  WeekBloodPressureResultAverage.fromJson(item),
                );
              }
            }

            // Parse year averages
            if (data['yearList'] != null) {
              for (var item in (data['yearList'] as List)) {
                _yearBloodPressureResultAverage.add(
                  YearBloodPressureResultAverage.fromJson(item),
                );
              }
            }
          }
        },
      );

      // Fetch blood pressure results
      final resultsResponse = await healthTrackersRepo.getBloodPressureResults();

      resultsResponse.fold(
        // (failure) => errorHandlerService.handleError(failure: failure),
        (failure) => {},
        (apiModel) {
          final data = apiModel.data;
          if (data is Map) {
            // Clear existing data
            _monthBloodPressureResult.clear();
            _weekBloodPressureResult.clear();
            _yearBloodPressureResult.clear();

            // Parse week results
            if (data['weekList'] != null) {
              for (var item in (data['weekList'] as List)) {
                _weekBloodPressureResult.add(BloodPressureResult.fromJson(item));
              }
            }

            // Parse month results
            if (data['monthList'] != null) {
              for (var item in (data['monthList'] as List)) {
                _monthBloodPressureResult.add(BloodPressureResult.fromJson(item));
              }
            }

            // Parse year results
            if (data['yearList'] != null) {
              for (var item in (data['yearList'] as List)) {
                _yearBloodPressureResult.add(BloodPressureResult.fromJson(item));
              }
            }
          }
        },
      );
    } catch (e) {
      log('Error in getBloodPressure: $e');
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  /// Add or Update blood pressure result
  Future<bool> addOrUpdateBloodPressureResult({
    required String bloodPressureDate,
    required String diastolicPressure,
    required String systolicePressure,
    required int measuredArm,
    int? lineItemNo,
    bool isUpdate = false,
  }) async {
    try {
      final result = isUpdate
          ? await healthTrackersRepo.updateBloodPressureResult(
              bloodPressureDate: bloodPressureDate,
              diastolicPressure: diastolicPressure,
              systolicePressure: systolicePressure,
              measuredArm: measuredArm,
              lineItemNo: lineItemNo!,
            )
          : await healthTrackersRepo.addBloodPressureResult(
              bloodPressureDate: bloodPressureDate,
              diastolicPressure: diastolicPressure,
              systolicePressure: systolicePressure,
              measuredArm: measuredArm,
            );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful add/update
          await getBloodPressure();
        },
      );

      return success;
    } catch (e) {
      log('Error in addOrUpdateBloodPressureResult: $e');
      return false;
    }
  }

  /// Delete blood pressure result
  Future<bool> deleteBloodPressureResult({
    required int lineItemNo,
  }) async {
    try {
      final result = await healthTrackersRepo.deactivateBloodPressureStatus(
        lineItemNo: lineItemNo,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful delete
          await getBloodPressure();
        },
      );

      return success;
    } catch (e) {
      log('Error in deleteBloodPressureResult: $e');
      return false;
    }
  }

  /// Send blood pressure report by email
  Future<bool> sendBloodPressureReportByEmail({
    required String email,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    try {
      final result = await healthTrackersRepo.sendBloodPressureReportByEmail(
        email: email,
      );

      bool success = false;

      result.fold(
        (failure) {
          errorHandlerService.handleError(failure: failure);
          if (onFailure != null) onFailure("Failed to send report by email");
        },
        (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess();
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendBloodPressureReportByEmail: $e');

      if (onFailure != null) onFailure("An error occurred");
      return false;
    }
  }

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

  /// Fetch blood sugar averages and results
  Future<void> getBloodSugar() async {
    isLoading = true;
    notifyListeners();

    try {
      // Fetch blood sugar averages
      final averageResult = await healthTrackersRepo.getDiabeticResultAverage();

      averageResult.fold(
        (failure) {},
        (apiModel) {
          final data = apiModel.data;
          if (data is Map) {
            // Clear existing data
            _monthDiabeticResultAverage.clear();
            _weekDiabeticResultAverage.clear();
            _yearDiabeticResultAverage.clear();

            // Parse month averages
            if (data['monthAverageList'] != null) {
              for (var item in (data['monthAverageList'] as List)) {
                _monthDiabeticResultAverage.add(
                  MonthDiabeticResultAverage.fromJson(item),
                );
              }
            }

            // Parse week averages
            if (data['weekAverageList'] != null) {
              for (var item in (data['weekAverageList'] as List)) {
                _weekDiabeticResultAverage.add(
                  WeekDiabeticResultAverage.fromJson(item),
                );
              }
            }

            // Parse year averages
            if (data['yearAverageList'] != null) {
              for (var item in (data['yearAverageList'] as List)) {
                _yearDiabeticResultAverage.add(
                  YearDiabeticResultAverage.fromJson(item),
                );
              }
            }
          }
        },
      );

      // Fetch blood sugar results
      final resultsResponse = await healthTrackersRepo.getDiabeticResults();

      resultsResponse.fold(
        // (failure) => errorHandlerService.handleError(failure: failure),
        (failure) {},
        (apiModel) {
          final data = apiModel.data;
          if (data is Map) {
            // Clear existing data
            _monthDiabeticPatientResult.clear();
            _weekDiabeticPatientResult.clear();
            _yearDiabeticPatientResult.clear();

            // Parse week results
            if (data['weekResultList'] != null) {
              for (var item in (data['weekResultList'] as List)) {
                _weekDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item));
              }
            }

            // Parse month results
            if (data['monthResultList'] != null) {
              for (var item in (data['monthResultList'] as List)) {
                _monthDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item));
              }
            }

            // Parse year results
            if (data['yearResultList'] != null) {
              for (var item in (data['yearResultList'] as List)) {
                _yearDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item));
              }
            }
          }
        },
      );
    } catch (e) {
      log('Error in getBloodSugar: $e');
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  /// Add new blood sugar result
  Future<bool> addBloodSugarResult({
    required String bloodSugarDateChart,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
  }) async {
    try {
      final result = await healthTrackersRepo.addDiabeticResult(
        bloodSugarDateChart: bloodSugarDateChart,
        bloodSugarResult: bloodSugarResult,
        diabeticUnit: diabeticUnit,
        measuredTime: measuredTime,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful add
          await getBloodSugar();
        },
      );

      return success;
    } catch (e) {
      log('Error in addBloodSugarResult: $e');
      return false;
    }
  }

  /// Update existing blood sugar result
  Future<bool> updateBloodSugarResult({
    required DateTime month,
    required DateTime hour,
    required String bloodSugarResult,
    required String diabeticUnit,
    required int measuredTime,
    required int lineItemNo,
  }) async {
    try {
      final result = await healthTrackersRepo.updateDiabeticResult(
        month: month,
        hour: hour,
        bloodSugarResult: bloodSugarResult,
        diabeticUnit: diabeticUnit,
        measuredTime: measuredTime,
        lineItemNo: lineItemNo,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful update
          await getBloodSugar();
        },
      );

      return success;
    } catch (e) {
      log('Error in updateBloodSugarResult: $e');
      return false;
    }
  }

  /// Delete blood sugar result
  Future<bool> deleteBloodSugarResult({
    required int lineItemNo,
  }) async {
    try {
      final result = await healthTrackersRepo.deactivateDiabeticStatus(
        lineItemNo: lineItemNo,
      );

      bool success = false;

      result.fold(
        (failure) => errorHandlerService.handleError(failure: failure),
        (apiModel) async {
          success = true;
          // Refresh data after successful delete
          await getBloodSugar();
        },
      );

      return success;
    } catch (e) {
      log('Error in deleteBloodSugarResult: $e');
      return false;
    }
  }

  /// Send blood sugar report by email
  Future<bool> sendBloodSugarReportByEmail({
    required String email,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    try {
      final result = await healthTrackersRepo.sendBloodSugarReportByEmail(
        email: email,
      );

      bool success = false;

      result.fold(
        (failure) {
          errorHandlerService.handleError(failure: failure);
          if (onFailure != null) onFailure("Failed to send report by email");
        },
        (apiModel) {
          success = true;
          if (onSuccess != null) onSuccess();
        },
      );

      notifyListeners();

      return success;
    } catch (e) {
      log('Error in sendBloodSugarReportByEmail: $e');
      if (onFailure != null) onFailure("An error occurred");
      return false;
    }
  }

  // Validation method - returns true if valid, false if errors exist
  // Shows only the first error encountered
  bool validateBloodSugarEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Clear all previous errors
    _bloodSugarError = null;
    _bloodSugarMeasureTimeError = null;
    _dateError = null;
    _timeError = null;

    // Validate blood sugar value - stop at first error
    if (bloodSugarController.text.trim().isEmpty) {
      _bloodSugarError = isArabic ? "الرجاء إدخال مستوى سكر الدم" : "Please enter blood sugar value";
      notifyListeners();
      return false;
    }

    final bloodSugarValue = double.tryParse(bloodSugarController.text.trim());
    if (bloodSugarValue == null) {
      _bloodSugarError = isArabic ? "الرجاء إدخال رقم صحيح" : "Please enter a valid number";
      notifyListeners();
      return false;
    }

    if (bloodSugarValue <= 0) {
      _bloodSugarError = isArabic ? "يجب أن يكون مستوى سكر الدم أكبر من 0" : "Blood sugar value must be greater than 0";
      notifyListeners();
      return false;
    }

    if (bloodSugarValue > 1000) {
      _bloodSugarError = isArabic ? "مستوى سكر الدم يبدو مرتفع جداً. يرجى التحقق وإدخالها مرة أخرى" : "Blood sugar value seems too high. Please check and enter again";
      notifyListeners();
      return false;
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      _dateError = isArabic ? "الرجاء اختيار التاريخ والوقت" : "Please select date and time";
      notifyListeners();
      return false;
    }

    // Validate measure time
    if (_selectedBloodSugarMeasureTime.isEmpty) {
      _bloodSugarMeasureTimeError = isArabic ? "الرجاء اختيار وقت القياس" : "Please select when the measurement was taken";
      notifyListeners();
      return false;
    }

    notifyListeners();
    return true;
  }

  // Old validation method kept for reference
  String? _validateBloodSugarEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate blood sugar value
    if (bloodSugarController.text.trim().isEmpty) {
      return isArabic ? "الرجاء إدخال مستوى سكر الدم" : "Please enter blood sugar value";
    }

    final bloodSugarValue = double.tryParse(bloodSugarController.text.trim());
    if (bloodSugarValue == null) {
      return isArabic ? "الرجاء إدخال رقم صحيح" : "Please enter a valid number";
    }

    if (bloodSugarValue <= 0) {
      return isArabic ? "يجب أن يكون مستوى سكر الدم أكبر من 0" : "Blood sugar value must be greater than 0";
    }

    // Validate reasonable range (typical ranges)
    if (bloodSugarValue > 1000) {
      return isArabic ? "مستوى سكر الدم يبدو مرتفع جداً. يرجى التحقق وإدخالها مرة أخرى" : "Blood sugar value seems too high. Please check and enter again";
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      return isArabic ? "الرجاء اختيار التاريخ والوقت" : "Please select date and time";
    }

    // Validate measure time
    if (_selectedBloodSugarMeasureTime.isEmpty) {
      return isArabic ? "الرجاء اختيار وقت القياس" : "Please select when the measurement was taken";
    }

    return null; // No errors
  }

  // Save blood sugar entry with validation
  Future<void> saveBloodSugarEntry({
    required String dateTime,
    required String measureTime,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate
    final validationError = _validateBloodSugarEntry(dateTime);
    if (validationError != null) {
      _errorMessage = validationError;
      if (onFailure != null) onFailure(validationError);
      return;
    }

    // Clear previous error and show loading
    _errorMessage = null;
    isLoading = true;
    notifyListeners();

    try {
      // Get measure time index (0-based, but API expects 1-based)
      final measureTimeIndex = bloodSugarMeasureTimeEnList.indexOf(measureTime);

      // Call API
      final success = await addBloodSugarResult(
        bloodSugarDateChart: dateTime,
        bloodSugarResult: bloodSugarController.text.trim(),
        diabeticUnit: _selectedBloodSugarUnit,
        measuredTime: measureTimeIndex >= 0 ? measureTimeIndex : 0,
      );

      isLoading = false;

      if (success) {
        // Clear form after successful save
        bloodSugarController.clear();
        _selectedBloodSugarMeasureTime = '';
        notifyListeners();
        if (onSuccess != null) onSuccess();
      } else {
        _errorMessage = isArabic ? "فشل حفظ قراءة سكر الدم. يرجى المحاولة مرة أخرى" : "Failed to save blood sugar entry. Please try again";
        notifyListeners();
        if (onFailure != null) onFailure(_errorMessage!);
      }
    } catch (e) {
      log('Error in saveBloodSugarEntry: $e');
      _errorMessage = isArabic ? "حدث خطأ. يرجى المحاولة مرة أخرى" : "An error occurred. Please try again";
      isLoading = false;
      notifyListeners();
      if (onFailure != null) onFailure(_errorMessage!);
    }
  }

  // ==================== WEIGHT ENTRY METHODS ====================

  // Validate weight entry before saving - returns true if valid, false if errors exist
  // Shows only the first error encountered
  bool validateWeightEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Clear all previous errors
    _weightError = null;
    _dateError = null;
    _timeError = null;

    // Validate weight value - stop at first error
    final weightValue = weightController.text.trim();
    if (weightValue.isEmpty) {
      _weightError = isArabic ? "الرجاء إدخال قيمة الوزن" : "Please enter weight value";
      notifyListeners();
      return false;
    }
    
    // Check if it's a valid number
    final parsedValue = double.tryParse(weightValue);
    if (parsedValue == null || parsedValue <= 0) {
      _weightError = isArabic ? "الرجاء إدخال قيمة وزن صحيحة" : "Please enter a valid weight value";
      notifyListeners();
      return false;
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      _dateError = isArabic ? "الرجاء تحديد التاريخ والوقت" : "Please select date and time";
      notifyListeners();
      return false;
    }

    notifyListeners();
    return true;
  }

  // Old validation method kept for reference
  String? _validateWeightEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate weight value
    final weightValue = weightController.text.trim();
    if (weightValue.isEmpty) {
      return isArabic ? "الرجاء إدخال قيمة الوزن" : "Please enter weight value";
    }

    // Check if it's a valid number
    final parsedValue = double.tryParse(weightValue);
    if (parsedValue == null || parsedValue <= 0) {
      return isArabic ? "الرجاء إدخال قيمة وزن صحيحة" : "Please enter a valid weight value";
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      return isArabic ? "الرجاء تحديد التاريخ والوقت" : "Please select date and time";
    }

    return null; // No errors
  }

  // Save weight entry with validation
  Future<void> saveWeightEntry({
    required String dateTime,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate
    final validationError = _validateWeightEntry(dateTime);
    if (validationError != null) {
      _errorMessage = validationError;
      if (onFailure != null) onFailure(validationError);
      return;
    }

    // Clear previous error and show loading
    _errorMessage = null;
    isLoading = true;
    notifyListeners();

    try {
      // Get weight unit index (0 = kg, 1 = lb)
      final weightUnitIndex = weightUnits.indexOf(_selectedWeightUnit);

      // Call API
      final success = await addWeightResult(
        weightDate: dateTime,
        weightMeasured: weightController.text.trim(),
        weightUnit: weightUnitIndex >= 0 ? weightUnitIndex : 0,
      );

      isLoading = false;

      if (success) {
        // Clear form after successful save
        weightController.clear();
        notifyListeners();
        if (onSuccess != null) onSuccess();
      } else {
        _errorMessage = isArabic ? "فشل حفظ قراءة الوزن. يرجى المحاولة مرة أخرى" : "Failed to save weight entry. Please try again";
        notifyListeners();
        if (onFailure != null) onFailure(_errorMessage!);
      }
    } catch (e) {
      log('Error in saveWeightEntry: $e');
      _errorMessage = isArabic ? "حدث خطأ. يرجى المحاولة مرة أخرى" : "An error occurred. Please try again";
      isLoading = false;
      notifyListeners();
      if (onFailure != null) onFailure(_errorMessage!);
    }
  }

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

  // Validate blood pressure entry before saving - returns true if valid, false if errors exist
  // Shows only the first error encountered
  bool validateBloodPressureEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Clear all previous errors
    _systolicError = null;
    _diastolicError = null;
    _measuredArmError = null;
    _dateError = null;
    _timeError = null;

    // Validate systolic value - stop at first error
    final systolicValue = systolicController.text.trim();
    if (systolicValue.isEmpty) {
      _systolicError = isArabic ? "الرجاء إدخال القيمة الانقباضية" : "Please enter systolic value";
      notifyListeners();
      return false;
    }
    
    final parsedSystolic = int.tryParse(systolicValue);
    if (parsedSystolic == null || parsedSystolic <= 0) {
      _systolicError = isArabic ? "الرجاء إدخال قيمة صحيحة للضغط الانقباضي" : "Please enter a valid systolic value";
      notifyListeners();
      return false;
    }

    // Validate diastolic value
    final diastolicValue = diastolicController.text.trim();
    if (diastolicValue.isEmpty) {
      _diastolicError = isArabic ? "الرجاء إدخال قيمة الضغط الانبساطي" : "Please enter diastolic value";
      notifyListeners();
      return false;
    }
    
    final parsedDiastolic = int.tryParse(diastolicValue);
    if (parsedDiastolic == null || parsedDiastolic <= 0) {
      _diastolicError = isArabic ? "الرجاء إدخال قيمة صحيحة للضغط الانبساطي" : "Please enter a valid diastolic value";
      notifyListeners();
      return false;
    }

    // Validate arm selection
    if (_selectedMeasuredArm.isEmpty) {
      _measuredArmError = isArabic ? "الرجاء اختيار الذراع المقاسة" : "Please select measured arm";
      notifyListeners();
      return false;
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      _dateError = isArabic ? "الرجاء تحديد التاريخ والوقت" : "Please select date and time";
      notifyListeners();
      return false;
    }

    notifyListeners();
    return true;
  }

  // Old validation method kept for reference
  String? _validateBloodPressureEntry(String dateTime) {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate systolic value
    final systolicValue = systolicController.text.trim();
    if (systolicValue.isEmpty) {
      return isArabic ? "الرجاء إدخال القيمة الانقباضية" : "Please enter systolic value";
    }
    final parsedSystolic = int.tryParse(systolicValue);
    if (parsedSystolic == null || parsedSystolic <= 0) {
      return isArabic ? "الرجاء إدخال قيمة صحيحة للضغط الانقباضي" : "Please enter a valid systolic value";
    }

    // Validate diastolic value
    final diastolicValue = diastolicController.text.trim();
    if (diastolicValue.isEmpty) {
      return isArabic ? "الرجاء إدخال قيمة الضغط الانبساطي" : "Please enter diastolic value";
    }
    final parsedDiastolic = int.tryParse(diastolicValue);
    if (parsedDiastolic == null || parsedDiastolic <= 0) {
      return isArabic ? "الرجاء إدخال قيمة صحيحة للضغط الانبساطي" : "Please enter a valid diastolic value";
    }

    // Validate arm selection
    if (_selectedMeasuredArm.isEmpty) {
      return isArabic ? "الرجاء اختيار الذراع المقاسة" : "Please select measured arm";
    }

    // Validate date time
    if (dateTime.trim().isEmpty) {
      return isArabic ? "الرجاء تحديد التاريخ والوقت" : "Please select date and time";
    }

    return null; // No errors
  }

  // Save blood pressure entry with validation
  Future<void> saveBloodPressureEntry({
    required String dateTime,
    Function()? onSuccess,
    Function(String error)? onFailure,
  }) async {
    final isArabic = getIt.get<AppState>().isArabic();

    // Validate
    final validationError = _validateBloodPressureEntry(dateTime);
    if (validationError != null) {
      _errorMessage = validationError;
      if (onFailure != null) onFailure(validationError);
      return;
    }

    // Clear previous error and show loading
    _errorMessage = null;
    isLoading = true;
    notifyListeners();

    try {
      // Get measured arm index (0 = Left Arm, 1 = Right Arm)
      final measuredArmIndex = measuredArmListEn.indexOf(_selectedMeasuredArm);

      // Call API
      final success = await addOrUpdateBloodPressureResult(
        bloodPressureDate: dateTime,
        systolicePressure: systolicController.text.trim(),
        diastolicPressure: diastolicController.text.trim(),
        measuredArm: measuredArmIndex >= 0 ? measuredArmIndex : 0,
        isUpdate: false,
      );

      isLoading = false;

      if (success) {
        // Clear form after successful save
        systolicController.clear();
        diastolicController.clear();
        _selectedMeasuredArm = '';
        notifyListeners();
        if (onSuccess != null) onSuccess();
      } else {
        _errorMessage = isArabic ? "فشل حفظ قراءة ضغط الدم. يرجى المحاولة مرة أخرى" : "Failed to save blood pressure entry. Please try again";
        notifyListeners();
        if (onFailure != null) onFailure(_errorMessage!);
      }
    } catch (e) {
      log('Error in saveBloodPressureEntry: $e');
      _errorMessage = isArabic ? "حدث خطأ. يرجى المحاولة مرة أخرى" : "An error occurred. Please try again";
      isLoading = false;
      notifyListeners();
      if (onFailure != null) onFailure(_errorMessage!);
    }
  }

  @override
  void dispose() {
    bloodSugarController.dispose();
    weightController.dispose();
    systolicController.dispose();
    diastolicController.dispose();
    super.dispose();
  }

  Future<void> downloadReport(HealthTrackerTypeEnum trackerType, {required  Function(dynamic report) onSuccess}) async {
    switch (trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        await downloadBloodSugerReport(
            onSuccess : (value){
              onSuccess(value);
            }
        );
        break;
      case HealthTrackerTypeEnum.bloodPressure:
        await downloadBloodPressureReport(
            onSuccess : (value){
              onSuccess(value);
            }
        );
        break;
      case HealthTrackerTypeEnum.weightTracker:
        await downloadWeightReport(
            onSuccess : (value){
              onSuccess(value);
            }
        );
        break;
    }
  }
}
