import 'package:easy_localization/easy_localization.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/common_models/data_points.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/vital_sign_respo_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/vital_sign_ui_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart';
import 'package:provider/provider.dart';

import 'dart:ui' as ui;

/// Which vital sign is being shown in the details screen.
enum VitalSignMetric {
  bmi,
  height,
  weight,
  bloodPressure,
  temperature,
  heartRate,
  respiratoryRate,
}

class VitalSignDetailsArgs {
  final VitalSignMetric metric;
  final String title;
  final String icon;
  final String unit;

  /// Optional bounds used for graph shading and labels.
  final double? low;
  final double? high;

  const VitalSignDetailsArgs({
    required this.metric,
    required this.title,
    required this.icon,
    required this.unit,
    this.low,
    this.high,
  });
}

class VitalSignDetailsPage extends StatefulWidget {
  final VitalSignDetailsArgs args;

  const VitalSignDetailsPage({super.key, required this.args});

  @override
  State<VitalSignDetailsPage> createState() => _VitalSignDetailsPageState();
}

class _VitalSignDetailsPageState extends State<VitalSignDetailsPage> {
  bool _isGraphVisible = true;

  VitalSignDetailsArgs get args => widget.args;

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.vitalSignDetails.tr(context: context),
      child: Consumer<HmgServicesViewModel>(
        builder: (context, viewModel, child) {
          final latest = viewModel.vitalSignList.isNotEmpty ? viewModel.vitalSignList.first : null;

          final history = _buildSeries(viewModel.vitalSignList, args);
          final latestValueText = _latestValueText(latest);
          final status = _statusForLatest(latest);
          final scheme = VitalSignUiModel.scheme(status: status, label: args.title);

          return SingleChildScrollView(
            child: Column(
              spacing: 16.h,
              children: [
                _headerCard(
                  context,
                  title: args.title,
                  icon: args.icon,
                  valueText: latestValueText,
                  status: status,
                  scheme: scheme,
                  latestDate: latest?.vitalSignDate,
                ),
                _whatIsThisResultCard(context),
                _historyCard(context, history: history),
                Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 16.r,
                    hasShadow: false,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LocaleKeys.history.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
                      SizedBox(height: 16.h),
                      _buildHistoryList(context, history),
                    ],
                  ).paddingSymmetrical(16.h, 16.h),
                ),
              ],
            ).paddingAll(24.h),
          );
        },
      ),
    );
  }

  Widget _headerCard(
    BuildContext context, {
    required String title,
    required String icon,
    required String valueText,
    required VitalSignStatus? status,
    required VitalSignUiModel scheme,
    required DateTime? latestDate,
  }) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      padding: EdgeInsets.all(16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 8.h,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  title.toText28(isBold: true, color: AppColors.textColor, letterSpacing: -1),
                ],
              ),
              SizedBox(height: 8.h),
              (latestDate != null
                      ? LocaleKeys.resultOf.tr(namedArgs: {'date': latestDate.toString().split(' ').first})
                      : LocaleKeys.resultOfNoDate.tr(context: context))
                  .toText11(isBold: true, color: AppColors.greyTextColor, isEnglishOnly: true),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Flexible(
                      child: valueText.toText28(
                        isBold: true,
                        color: scheme.iconFg,
                        letterSpacing: -2,
                        isEnglishOnly: true
                      ),
                    ),
                    SizedBox(width: 4.h),
                    if (status != null)
                      Directionality(
                        textDirection: ui.TextDirection.ltr,
                        child: Column(
                          spacing: 6.h,
                          children: [
                            VitalSignUiModel.statusToString(status).toText10(isBold: true, color: AppColors.greyTextColor),
                            Utils.buildSvgWithAssets(
                              icon: AppAssets.lab_result_indicator,
                              width: 21,
                              height: 23,
                              iconColor: scheme.iconFg,
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
          if (args.low != null || args.high != null)
            Text(
              _referenceText(context),
              style: TextStyle(
                fontSize: 12.f,
                fontWeight: FontWeight.w600,
                fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                color: AppColors.greyTextColor,
              ),
              softWrap: true,
            ),
        ],
      ),
    );
  }

  String _referenceText(BuildContext context) {
    if (args.low != null && args.high != null) {
      return LocaleKeys.referenceRangeBetween.tr(namedArgs: {
        'low': args.low.toString(),
        'high': args.high.toString(),
        'unit': args.unit ?? ''
      });
    }
    if (args.low != null) {
      return LocaleKeys.referenceRangeMin.tr(namedArgs: {
        'low': args.low.toString(),
        'unit': args.unit ?? ''
      });
    }
    if (args.high != null) {
      return LocaleKeys.referenceRangeMax.tr(namedArgs: {
        'high': args.high.toString(),
        'unit': args.unit ?? ''
      });
    }
    return '';
  }

  Widget _whatIsThisResultCard(BuildContext context) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      padding: EdgeInsets.all(16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 8.h,
        children: [
          LocaleKeys.whatIsThisResult.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
          _descriptionText(context).toText12(isBold: true, color: AppColors.textColorLight),
        ],
      ),
    );
  }

  Widget _historyCard(BuildContext context, {required List<DataPoint> history}) {
    // For graph display, use only the last 5 data points to avoid performance issues
    final graphHistory = _isGraphVisible && history.length > 5
        ? history.sublist(history.length - 5)
        : history;

    // For blood pressure, we need both systolic and diastolic series
    List<DataPoint>? secondaryHistory;
    if (args.metric == VitalSignMetric.bloodPressure) {
      final fullSecondaryHistory = _buildBloodPressureDiastolicSeries(
        context.read<HmgServicesViewModel>().vitalSignList,
      );
      // Also limit secondary history to last 5 for graph
      secondaryHistory = _isGraphVisible && fullSecondaryHistory.length > 5
          ? fullSecondaryHistory.sublist(fullSecondaryHistory.length - 5)
          : fullSecondaryHistory;
    }

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      height: _isGraphVisible
          ? 260.h
          : (history.length < 3)
              ? (history.length * 64) + 80.h
              : 260.h,
      padding: EdgeInsets.all(15.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              LocaleKeys.historyFlowchart.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Container(
                  //   width: 24.h,
                  //   height: 24.h,
                  //   alignment: Alignment.center,
                  //   child: InkWell(
                  //     onTap: () {
                  //       setState(() {
                  //         _isGraphVisible = !_isGraphVisible;
                  //       });
                  //     },
                  //     child: Utils.buildSvgWithAssets(
                  //       icon: _isGraphVisible ? AppAssets.ic_list : AppAssets.ic_graph,
                  //       width: 24.h,
                  //       height: 24.h,
                  //     ),
                  //   ),
                  // ),
                  // SizedBox(width: 16.h),
                  // Container(
                  //   width: 24.h,
                  //   height: 24.h,
                  //   alignment: Alignment.center,
                  //   child: Utils.buildSvgWithAssets(
                  //     icon: AppAssets.ic_date_filter,
                  //     width: 24.h,
                  //     height: 24.h,
                  //   ),
                  // ),
                ],
              ),
            ],
          ).paddingOnly(bottom: _isGraphVisible ? 16.h : 24.h),

          if (history.isEmpty)
            Utils.getNoDataWidget(context, noDataText: LocaleKeys.noHistoryAvailable.tr(context: context), isSmallWidget: true)
          else if (_isGraphVisible)
            _buildHistoryGraph(graphHistory, secondaryHistory: secondaryHistory)
          else
            _buildHistoryList(context, history),
        ],
      ),
    );
  }

  Widget _buildHistoryGraph(List<DataPoint> history, {List<DataPoint>? secondaryHistory}) {
    final minY = _minY(history, secondaryHistory: secondaryHistory);
    final maxY = _maxY(history, secondaryHistory: secondaryHistory);
    final isRTL = getIt.get<AppState>().isArabic();

    return CustomGraph(
      dataPoints: history,
      secondaryDataPoints: secondaryHistory,
      makeGraphBasedOnActualValue: true,
      leftLabelReservedSize: 40,
      showGridLines: true,
      showShadow: false,
      isRTL: isRTL,
      leftLabelInterval: _leftInterval(history, secondaryHistory: secondaryHistory),
      maxY: maxY,
      minY: minY,
      maxX: history.length.toDouble() - .75,
      horizontalInterval: .01,
      leftLabelFormatter: (value) {
        // Format value to 2 decimal places for consistency
        value = double.parse(value.toStringAsFixed(2));
        return _axisLabel(value.toStringAsFixed(2));
      },
      getDrawingHorizontalLine: (value) {
        value = double.parse(value.toStringAsFixed(2));
        // Draw solid reference lines for high/low bounds (matching lab result style)
        if (args.high != null && (value - args.high!).abs() < 0.1) {
          return FlLine(
            color: AppColors.bgGreenColor.withValues(alpha: 0.6),
            strokeWidth: 1,
          );
        }
        if (args.low != null && (value - args.low!).abs() < 0.1) {
          return FlLine(
            color: AppColors.bgGreenColor.withValues(alpha: 0.6),
            strokeWidth: 1,
          );
        }
        // Hide other grid lines
        return FlLine(
          color: Colors.transparent,
          strokeWidth: 1,
        );
      },
      graphColor: AppColors.textColor.withValues(alpha: 90 / 255),
      secondaryGraphColor: AppColors.textColor.withValues(alpha: 90 / 255),
      graphShadowColor: AppColors.greyColor.withValues(alpha: 0.5),
      graphGridColor: AppColors.textColor.withValues(alpha: 0.4),
        bottomLabelFormatter: (value, data) {
          if (data.isEmpty) return const SizedBox.shrink();
          if (value == 0) return _bottomLabel(data[value.toInt()].label);
          if (value == data.length - 1) return _bottomLabel(data[value.toInt()].label, isLast: true);
          if (value == ((data.length - 1) / 2)) return _bottomLabel(data[value.toInt()].label);
          return const SizedBox.shrink();
        },
      rangeAnnotations: _rangeAnnotations(history, secondaryHistory: secondaryHistory),
      minX: (history.length == 1) ? null : -.2,
      scrollDirection: Axis.horizontal,
      height: 180.h,
    );
  }


  Widget _buildHistoryList(BuildContext context, List<DataPoint> history) {
    final items = history.reversed.toList();
    final height = items.length < 3 ? items.length * 64.0 : 180.h;

    // Get diastolic values if this is blood pressure
    List<DataPoint>? secondaryItems;
    if (args.metric == VitalSignMetric.bloodPressure) {
      final viewModel = context.read<HmgServicesViewModel>();
      final secondaryHistory = _buildBloodPressureDiastolicSeries(viewModel.vitalSignList);
      secondaryItems = secondaryHistory.reversed.toList();
    }

    return SizedBox(
      height: height,
      child: ListView.separated(
        padding: EdgeInsets.zero,
        itemCount: items.length,
        separatorBuilder: (_, __) => Divider(
          color: AppColors.borderOnlyColor.withValues(alpha: 0.1),
          height: 1,
        ),
        itemBuilder: (context, index) {
          final dp = items[index];

          // Build the value text based on metric type
          String valueText;
          if (args.metric == VitalSignMetric.bloodPressure && secondaryItems != null && index < secondaryItems.length) {
            // Show systolic/diastolic for blood pressure
            final diastolic = secondaryItems[index];
            valueText = '${dp.actualValue}/${diastolic.actualValue} ${dp.unitOfMeasurement ?? ''}';
          } else {
            // Show single value for other metrics
            valueText = '${dp.actualValue} ${dp.unitOfMeasurement ?? ''}';
          }

          return Padding(
            padding: EdgeInsets.symmetric(vertical: 12.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                dp.displayTime.toText12(color: AppColors.greyTextColor, isBold: true, isEnglishOnly: true),
                Directionality(
                  textDirection: ui.TextDirection.ltr,
                  child: valueText.toText12(
                    color: AppColors.textColor,
                    isBold: true,
                    isEnglishOnly: true
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  double _minY(List<DataPoint> points, {List<DataPoint>? secondaryHistory}) {
    // IMPORTANT: y-axis uses actual numeric values (from actualValue).
    final values = points.map((e) => double.tryParse(e.actualValue) ?? 0).toList();

    // Include secondary data points if provided (for blood pressure)
    if (secondaryHistory != null && secondaryHistory.isNotEmpty) {
      values.addAll(secondaryHistory.map((e) => double.tryParse(e.actualValue) ?? 0));
    }

    final min = values.reduce((a, b) => a < b ? a : b);
    final double boundLow = args.low ?? min;
    return (min < boundLow ? min : boundLow) - 1;
  }

  double _maxY(List<DataPoint> points, {List<DataPoint>? secondaryHistory}) {
    // IMPORTANT: y-axis uses actual numeric values (from actualValue).
    final values = points.map((e) => double.tryParse(e.actualValue) ?? 0).toList();

    // Include secondary data points if provided (for blood pressure)
    if (secondaryHistory != null && secondaryHistory.isNotEmpty) {
      values.addAll(secondaryHistory.map((e) => double.tryParse(e.actualValue) ?? 0));
    }

    final max = values.reduce((a, b) => a > b ? a : b);
    final double boundHigh = args.high ?? max;
    return (max > boundHigh ? max : boundHigh) + 1;
  }

  double _leftInterval(List<DataPoint> points, {List<DataPoint>? secondaryHistory}) {
    // Keep it stable; graph will mostly show just two labels.
    final range = (_maxY(points, secondaryHistory: secondaryHistory) - _minY(points, secondaryHistory: secondaryHistory)).abs();
    if (range <= 0) return 1;
    return (range / 4).clamp(1, 20);
  }

  RangeAnnotations? _rangeAnnotations(List<DataPoint> points, {List<DataPoint>? secondaryHistory}) {
    if (args.low == null && args.high == null) return null;

    final minY = _minY(points, secondaryHistory: secondaryHistory);
    final maxY = _maxY(points, secondaryHistory: secondaryHistory);

    final List<HorizontalRangeAnnotation> ranges = [];

    // Below low reference (transparent - matching lab result style)
    if (args.low != null) {
      ranges.add(
        HorizontalRangeAnnotation(
          y1: minY,
          y2: args.low!,
          color: Colors.transparent,
        ),
      );
    }

    // Normal range (light green shading - matching lab result style)
    if (args.low != null && args.high != null) {
      ranges.add(
        HorizontalRangeAnnotation(
          y1: args.low!,
          y2: args.high!,
          color: AppColors.bgGreenColor.withValues(alpha: 0.05),
        ),
      );
    }

    // Above high reference (transparent - matching lab result style)
    if (args.high != null) {
      ranges.add(
        HorizontalRangeAnnotation(
          y1: args.high!,
          y2: maxY,
          color: Colors.transparent,
        ),
      );
    }

    return RangeAnnotations(horizontalRangeAnnotations: ranges);
  }

  List<DataPoint> _buildSeries(List<VitalSignResModel> vitals, VitalSignDetailsArgs args) {
    final List<DataPoint> points = [];

    // Build a chronological series (oldest -> newest), skipping null/zero values.
    final sorted = List<VitalSignResModel>.from(vitals);
    sorted.sort((a, b) {
      final ad = a.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0);
      final bd = b.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0);
      return ad.compareTo(bd);
    });

    double? metricValue(VitalSignResModel v) {
      switch (args.metric) {
        case VitalSignMetric.bmi:
          return _toDouble(v.bodyMassIndex);
        case VitalSignMetric.height:
          return _toDouble(v.heightCm);
        case VitalSignMetric.weight:
          return _toDouble(v.weightKg);
        case VitalSignMetric.temperature:
          return _toDouble(v.temperatureCelcius);
        case VitalSignMetric.heartRate:
          return _toDouble(v.heartRate ?? v.pulseBeatPerMinute);
        case VitalSignMetric.respiratoryRate:
          return _toDouble(v.respirationBeatPerMinute);
        case VitalSignMetric.bloodPressure:
        // Graph systolic for primary series
          return _toDouble(v.bloodPressureHigher);
      }
    }

    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    double index = 0;
    for (final v in sorted) {
      final mv = metricValue(v);
      if (mv == null) continue;
      if (mv == 0) continue;

      final dt = v.vitalSignDate ?? DateTime.now();
      final label = '${monthNames[dt.month - 1]}, ${dt.year}';

      points.add(
        DataPoint(
          value: index,
          label: label,
          actualValue: mv.toStringAsFixed(0),
          time: dt,
          displayTime: '${dt.day}/${dt.month}/${dt.year}',
          unitOfMeasurement: args.unit,
        ),
      );
      index += 1;
    }

    return points;
  }

  /// Build diastolic blood pressure series for dual-line graph
  List<DataPoint> _buildBloodPressureDiastolicSeries(List<VitalSignResModel> vitals) {
    final List<DataPoint> points = [];

    // Build a chronological series (oldest -> newest), skipping null/zero values.
    final sorted = List<VitalSignResModel>.from(vitals);
    sorted.sort((a, b) {
      final ad = a.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0);
      final bd = b.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0);
      return ad.compareTo(bd);
    });

    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    double index = 0;
    for (final v in sorted) {
      final diastolic = _toDouble(v.bloodPressureLower);
      if (diastolic == null) continue;
      if (diastolic == 0) continue;

      final dt = v.vitalSignDate ?? DateTime.now();
      final label = '${monthNames[dt.month - 1]}, ${dt.year}';

      points.add(
        DataPoint(
          value: index,
          label: label,
          actualValue: diastolic.toStringAsFixed(0),
          time: dt,
          displayTime: '${dt.day}/${dt.month}/${dt.year}',
          unitOfMeasurement: args.unit,
        ),
      );
      index += 1;
    }

    return points;
  }

  double? _toDouble(dynamic v) {
    if (v == null) return null;
    if (v is num) {
      // Treat 0 as invalid for vital signs
      return v == 0 ? null : v.toDouble();
    }
    final parsed = double.tryParse(v.toString());
    // Treat 0 as invalid for vital signs
    return (parsed == null || parsed == 0) ? null : parsed;
  }

  String _latestValueText(VitalSignResModel? latest) {
    if (latest == null) return '--';

    switch (args.metric) {
      case VitalSignMetric.bmi:
        final v = _toDouble(latest.bodyMassIndex);
        return v == null ? '--' : v.toStringAsFixed(0);
      case VitalSignMetric.height:
        final v = _toDouble(latest.heightCm);
        return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}';
      case VitalSignMetric.weight:
        final v = _toDouble(latest.weightKg);
        return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}';
      case VitalSignMetric.temperature:
        final v = _toDouble(latest.temperatureCelcius);
        return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}';
      case VitalSignMetric.heartRate:
        final v = _toDouble(latest.heartRate ?? latest.pulseBeatPerMinute);
        return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}';
      case VitalSignMetric.respiratoryRate:
        final v = _toDouble(latest.respirationBeatPerMinute);
        return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}';
      case VitalSignMetric.bloodPressure:
        final s = _toDouble(latest.bloodPressureHigher);
        final d = _toDouble(latest.bloodPressureLower);
        if (s == null || d == null) return '--';
        return '${s.toStringAsFixed(0)}/${d.toStringAsFixed(0)}';
    }
  }

  VitalSignStatus? _statusForLatest(VitalSignResModel? latest) {
    if (latest == null) return null;

    switch (args.metric) {
      case VitalSignMetric.bmi:
        return VitalSignUiModel.bmiStatus(latest.bodyMassIndex);
      case VitalSignMetric.bloodPressure:
        return VitalSignUiModel.bloodPressureStatus(systolic: latest.bloodPressureHigher, diastolic: latest.bloodPressureLower);
      case VitalSignMetric.height:
        return null;
      case VitalSignMetric.weight:
        return VitalSignUiModel.weightStatus(latest.bodyMassIndex);
      case VitalSignMetric.temperature:
        return null;
      case VitalSignMetric.heartRate:
        final heartRateValue = _toDouble(latest.heartRate ?? latest.pulseBeatPerMinute);
        return (heartRateValue != null && heartRateValue > 0) ? VitalSignStatus.normal : null;
      case VitalSignMetric.respiratoryRate:
        final respiratoryValue = _toDouble(latest.respirationBeatPerMinute);
        return (respiratoryValue != null && respiratoryValue > 0) ? VitalSignStatus.normal : null;
    }
  }

  String _descriptionText(BuildContext context) {
    switch (args.metric) {
      case VitalSignMetric.bmi:
        return LocaleKeys.bmiDescription.tr(context: context);
      case VitalSignMetric.height:
        return LocaleKeys.heightDescription.tr(context: context);
      case VitalSignMetric.weight:
        return LocaleKeys.weightDescription.tr(context: context);
      case VitalSignMetric.bloodPressure:
        return LocaleKeys.bloodPressureDescription.tr(context: context);
      case VitalSignMetric.temperature:
        return LocaleKeys.temperatureDescription.tr(context: context);
      case VitalSignMetric.heartRate:
        return LocaleKeys.heartRateDescriptionVital.tr(context: context);
      case VitalSignMetric.respiratoryRate:
        return LocaleKeys.respiratoryRateDescription.tr(context: context);
    }
  }

  String _nextStepsText(BuildContext context) {
    switch (args.metric) {
      case VitalSignMetric.bmi:
        return LocaleKeys.bmiAdvice.tr(context: context);
      case VitalSignMetric.height:
        return LocaleKeys.heightAdvice.tr(context: context);
      case VitalSignMetric.weight:
        return LocaleKeys.weightAdvice.tr(context: context);
      case VitalSignMetric.bloodPressure:
        return LocaleKeys.bloodPressureAdvice.tr(context: context);
      case VitalSignMetric.temperature:
        return LocaleKeys.temperatureAdvice.tr(context: context);
      case VitalSignMetric.heartRate:
        return LocaleKeys.heartRateAdvice.tr(context: context);
      case VitalSignMetric.respiratoryRate:
        return LocaleKeys.respiratoryRateAdvice.tr(context: context);
    }
  }

  Widget _nextStepsCard(BuildContext context) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      padding: EdgeInsets.all(16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.whatShouldIDoNext.tr(context: context).toText16(isBold: true),
          SizedBox(height: 8.h),
          _nextStepsText(context).toText12(color: AppColors.greyTextColor, isBold: true, maxLine: 10),
        ],
      ),
    );
  }

  Widget _axisLabel(String value) {
    return Text(
      value,
      style: TextStyle(
        fontWeight: FontWeight.w600,
        fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
        fontSize: 8.f,
        color: AppColors.textColor,
      ),
    );
  }

  Widget _bottomLabel(String label, {bool isLast = false}) {
    return Padding(
      padding: EdgeInsetsDirectional.only(
        top: 8.0,
        end: isLast ? 16.h : 0,
      ),
      child: label.toText10(isBold: true, isEnglishOnly: true),
    );
  }

}
