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_export.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/enums.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.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/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/week_weight_measurement_result_average.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/features/health_trackers/health_trackers_view_model.dart';
import 'package:hmg_patient_app_new/presentation/health_trackers/widgets/tracker_last_value_card.dart';
import 'package:hmg_patient_app_new/services/dialog_service.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/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class HealthTrackerDetailPage extends StatefulWidget {
  final HealthTrackerTypeEnum trackerType;

  const HealthTrackerDetailPage({super.key, required this.trackerType});

  @override
  State<HealthTrackerDetailPage> createState() => _HealthTrackerDetailPageState();
}

class _HealthTrackerDetailPageState extends State<HealthTrackerDetailPage> {
  @override
  void initState() {
    super.initState();
    // Load data based on tracker type
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final viewModel = context.read<HealthTrackersViewModel>();
      await _loadTrackerData(viewModel);
    });
  }

  /// Load data based on tracker type
  Future<void> _loadTrackerData(HealthTrackersViewModel viewModel) async {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        await viewModel.getBloodSugar();
        break;
      case HealthTrackerTypeEnum.bloodPressure:
        await viewModel.getBloodPressure();
        break;
      case HealthTrackerTypeEnum.weightTracker:
        await viewModel.getWeight();
        break;
    }
  }

  /// Get page title based on tracker type
  String _getPageTitle() {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return LocaleKeys.bloodSugar.tr(context: context);
      case HealthTrackerTypeEnum.bloodPressure:
        return LocaleKeys.bloodPressure.tr(context: context);
      case HealthTrackerTypeEnum.weightTracker:
        return LocaleKeys.weight.tr(context: context);
    }
  }

  /// Get unit based on tracker type
  String _getUnit() {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return 'mg/dL';
      case HealthTrackerTypeEnum.bloodPressure:
        return 'mmHg';
      case HealthTrackerTypeEnum.weightTracker:
        return 'kg';
    }
  }

  /// Get empty state message based on tracker type
  String _getEmptyStateMessage() {
    final isArabic = getIt.get<AppState>().isArabic();

    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return isArabic ? "الرجاء إضافة قراءة جديدة لتتبع سكر الدم" : "Please add data to track your Blood Sugar";
      case HealthTrackerTypeEnum.bloodPressure:
        return isArabic ? "الرجاء إضافة قراءة جديدة لتتبع ضغط الدم" : "Please add data to track your Blood Pressure";
      case HealthTrackerTypeEnum.weightTracker:
        return isArabic ? "الرجاء إضافة قراءة جديدة لتتبع الوزن" : "Please add data to track your Weight";
    }
  }

  /// Check if data is empty based on tracker type
  bool _hasNoData(HealthTrackersViewModel viewModel) {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return viewModel.weekDiabeticPatientResult.isEmpty &&
            viewModel.monthDiabeticPatientResult.isEmpty &&
            viewModel.yearDiabeticPatientResult.isEmpty;
      case HealthTrackerTypeEnum.bloodPressure:
        return viewModel.weekBloodPressureResult.isEmpty && viewModel.monthBloodPressureResult.isEmpty && viewModel.yearBloodPressureResult.isEmpty;
      case HealthTrackerTypeEnum.weightTracker:
        return viewModel.weekWeightMeasurementResult.isEmpty &&
            viewModel.monthWeightMeasurementResult.isEmpty &&
            viewModel.yearWeightMeasurementResult.isEmpty;
    }
  }

  // Reusable method to build selection row widget
  Widget _buildSelectionRow({
    required String value,
    required String groupValue,
    required VoidCallback onTap,
    bool useUpperCase = false,
  }) {
    return SizedBox(
      height: 70.h,
      child: Row(
        spacing: 8.h,
        children: [
          Radio<String>(
            value: value,
            groupValue: groupValue,
            activeColor: AppColors.errorColor,
            onChanged: (_) => onTap(),
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          (useUpperCase ? value.toUpperCase() : value.toCamelCase)
              .toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1)
              .expanded,
        ],
      ).onPress(onTap),
    );
  }

  void _showSelectionBottomSheet({
    required BuildContext context,
    required String title,
    required List<String> items,
    required String selectedValue,
    required Function(String) onSelected,
    bool useUpperCase = false,
  }) {
    final dialogService = getIt.get<DialogService>();

    dialogService.showFamilyBottomSheetWithoutHWithChild(
      label: title,
      message: "",
      child: Container(
        padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h),
        decoration: BoxDecoration(color: AppColors.whiteColor, borderRadius: BorderRadius.circular(20.r)),
        child: ListView.separated(
          shrinkWrap: true,
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return _buildSelectionRow(
              value: item,
              groupValue: selectedValue,
              useUpperCase: useUpperCase,
              onTap: () {
                onSelected(item);
                Navigator.pop(context);
              },
            );
          },
          separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor),
        ),
      ),
      onOkPressed: () {},
    );
  }

  void _showHistoryDurationBottomsheet(BuildContext context, HealthTrackersViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectDuration.tr(),
      items: viewModel.durationFilters,
      selectedValue: viewModel.selectedDurationFilterDisplay,
      onSelected: viewModel.setFilterDuration,
    );
  }

  Widget buildHistoryListTile({required String title, required String subTitle, required String measureDesc, double? value}) {
    // Get status color and rotation based on value and tracker type
    Color statusColor = AppColors.successColor;
    double rotation = 0;

    if (value != null) {
      switch (widget.trackerType) {
        case HealthTrackerTypeEnum.bloodSugar:
          if (value < 70) {
            statusColor = AppColors.errorColor;
            rotation = 0; // pointing down
          } else if (value <= 100) {
            statusColor = AppColors.successColor;
            rotation = -3.14159 / 2; // pointing right
          } else if (value <= 125) {
            statusColor = AppColors.ratingColorYellow;
            rotation = 3.14159; // pointing up
          } else {
            statusColor = AppColors.errorColor;
            rotation = 3.14159; // pointing up
          }
          break;
        case HealthTrackerTypeEnum.bloodPressure:
          // Systolic pressure ranges
          if (value < 90) {
            statusColor = AppColors.errorColor;
            rotation = 0; // Low - pointing down
          } else if (value <= 120) {
            statusColor = AppColors.successColor;
            rotation = -3.14159 / 2; // Normal - pointing right
          } else if (value <= 140) {
            statusColor = AppColors.ratingColorYellow;
            rotation = 3.14159; // Elevated - pointing up
          } else {
            statusColor = AppColors.errorColor;
            rotation = 3.14159; // High - pointing up
          }
          break;
        case HealthTrackerTypeEnum.weightTracker:
          // Weight doesn't have good/bad indicators, just show neutral
          statusColor = AppColors.transparent;
          rotation = -3.14159 / 2; // pointing right (neutral)
          break;
      }
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                AppCustomChipWidget(labelText: title),
                if (measureDesc.isNotEmpty) ...[
                  SizedBox(width: 8.w),
                  AppCustomChipWidget(labelText: measureDesc),
                ],
              ],
            ),
            SizedBox(height: 4.h),
            subTitle.toText16(isBold: true, color: AppColors.textColor),
          ],
        ),
        Transform.rotate(
          angle: rotation,
          child: Utils.buildSvgWithAssets(
            icon: AppAssets.lowIndicatorIcon,
            iconColor: statusColor,
            height: 20.h,
            width: 20.h,
          ),
        ),
      ],
    ).paddingSymmetrical(0, 8.h);
  }

  Widget _buildHistoryGraphOrList() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Consumer(builder: (BuildContext context, HealthTrackersViewModel viewModel, Widget? child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    LocaleKeys.history.tr(context: context).toText16(isBold: true),
                    if (viewModel.isGraphView) ...[
                      SizedBox(width: 12.w),
                      InkWell(
                        onTap: () => _showHistoryDurationBottomsheet(context, viewModel),
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 6.h),
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            backgroundColor: AppColors.greyColor,
                            borderRadius: 8.r,
                            hasShadow: true,
                          ),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              viewModel.selectedDurationFilterDisplay.toText12(isBold: true),
                              SizedBox(width: 4.w),
                              Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 16.h),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
                InkWell(
                  onTap: () => viewModel.setGraphView(!viewModel.isGraphView),
                  child: AnimatedSwitcher(
                    duration: const Duration(milliseconds: 300),
                    transitionBuilder: (Widget child, Animation<double> animation) {
                      return FadeTransition(
                        opacity: animation,
                        child: ScaleTransition(
                          scale: animation,
                          child: child,
                        ),
                      );
                    },
                    child: Container(
                      key: ValueKey<bool>(viewModel.isGraphView),
                      child: Utils.buildSvgWithAssets(
                        icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon,
                        height: 24.h,
                        width: 24.h,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            if (!viewModel.isGraphView) _buildHistoryListView(viewModel) else ...[SizedBox(height: 16.h), _buildHistoryGraph()]
          ],
        );
      }),
    );
  }

  String _formatTime(DateTime time) {
    final hour = time.hour;
    final minute = time.minute;
    final hour12 = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour);
    final period = hour >= 12 ? 'PM' : 'AM';
    return '${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period';
  }

  String _getDayName(DateTime date) {
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return days[date.weekday - 1];
  }

  String _getMonthName(int monthNumber) {
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    if (monthNumber < 1 || monthNumber > 12) return 'Unknown';
    return months[monthNumber - 1];
  }

  Widget _buildHistoryListView(HealthTrackersViewModel viewModel) {
    List<Widget> listItems = [];
    final unit = _getUnit();

    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        listItems = _buildBloodSugarListItems(viewModel, unit);
        break;
      case HealthTrackerTypeEnum.bloodPressure:
        listItems = _buildBloodPressureListItems(viewModel);
        break;
      case HealthTrackerTypeEnum.weightTracker:
        listItems = _buildWeightListItems(viewModel, unit);
        break;
    }

    if (viewModel.isLoading) {
      return _buildLoadingShimmer().paddingOnly(top: 16.h);
    }

    if (listItems.isEmpty) {
      return _buildEmptyStateWidget();
    }

    return ListView.separated(
      padding: EdgeInsets.only(top: 16.h),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: listItems.length,
      separatorBuilder: (context, index) => SizedBox.shrink(),
      itemBuilder: (context, index) => listItems[index],
    );
  }

  /// Build list items for Blood Sugar
  List<Widget> _buildBloodSugarListItems(HealthTrackersViewModel viewModel, String unit) {
    List<Widget> listItems = [];
    final allResults = <dynamic>[];

    allResults.addAll(viewModel.weekDiabeticPatientResult);
    allResults.addAll(viewModel.monthDiabeticPatientResult);
    allResults.addAll(viewModel.yearDiabeticPatientResult);

    final seenIds = <String>{};
    final uniqueResults = allResults.where((result) {
      final id = '${result.lineItemNo}_${result.dateChart?.millisecondsSinceEpoch ?? 0}';
      if (seenIds.contains(id)) return false;
      seenIds.add(id);
      return true;
    }).toList();

    uniqueResults.sort((a, b) {
      final dateA = a.dateChart ?? DateTime(1900);
      final dateB = b.dateChart ?? DateTime(1900);
      return dateB.compareTo(dateA);
    });

    for (var result in uniqueResults) {
      final resultValue = result.resultValue?.toDouble() ?? 0.0;
      final value = result.resultValue?.toString() ?? '0';
      final resultUnit = result.unit ?? unit;
      final measuredDesc = result.measuredDesc ?? '';
      final date = result.dateChart;
      final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : '';
      final timeLabel = date != null ? _formatTime(date) : 'Unknown';
      final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown';
      final subTitleText = '$value $resultUnit';

      listItems.add(
        Column(
          children: [
            buildHistoryListTile(
              title: displayLabel,
              subTitle: subTitleText,
              value: resultValue,
              measureDesc: measuredDesc,
            ),
            Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h),
          ],
        ),
      );
    }
    return listItems;
  }

  /// Build list items for Blood Pressure
  List<Widget> _buildBloodPressureListItems(HealthTrackersViewModel viewModel) {
    List<Widget> listItems = [];
    final allResults = <dynamic>[];

    allResults.addAll(viewModel.weekBloodPressureResult);
    allResults.addAll(viewModel.monthBloodPressureResult);
    allResults.addAll(viewModel.yearBloodPressureResult);

    final seenIds = <String>{};
    final uniqueResults = allResults.where((result) {
      final id = '${result.lineItemNo}_${result.bloodPressureDate?.millisecondsSinceEpoch ?? 0}';
      if (seenIds.contains(id)) return false;
      seenIds.add(id);
      return true;
    }).toList();

    uniqueResults.sort((a, b) {
      final dateA = a.bloodPressureDate ?? DateTime(1900);
      final dateB = b.bloodPressureDate ?? DateTime(1900);
      return dateB.compareTo(dateA);
    });

    for (var result in uniqueResults) {
      final systolic = result.systolicePressure ?? 0;
      final diastolic = result.diastolicPressure ?? 0;
      final measuredArmDesc = result.measuredArmDesc ?? '';
      final date = result.bloodPressureDate;
      final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : '';
      final timeLabel = date != null ? _formatTime(date) : 'Unknown';
      final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown';
      final subTitleText = '$systolic/$diastolic mmHg';

      listItems.add(
        Column(
          children: [
            buildHistoryListTile(
              title: displayLabel,
              subTitle: subTitleText,
              value: systolic.toDouble(),
              measureDesc: measuredArmDesc,
            ),
            Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h),
          ],
        ),
      );
    }
    return listItems;
  }

  /// Build list items for Weight
  List<Widget> _buildWeightListItems(HealthTrackersViewModel viewModel, String unit) {
    List<Widget> listItems = [];
    final allResults = <dynamic>[];

    allResults.addAll(viewModel.weekWeightMeasurementResult);
    allResults.addAll(viewModel.monthWeightMeasurementResult);
    allResults.addAll(viewModel.yearWeightMeasurementResult);

    final seenIds = <String>{};
    final uniqueResults = allResults.where((result) {
      final id = '${result.lineItemNo}_${result.weightDate?.millisecondsSinceEpoch ?? 0}';
      if (seenIds.contains(id)) return false;
      seenIds.add(id);
      return true;
    }).toList();

    uniqueResults.sort((a, b) {
      final dateA = a.weightDate ?? DateTime(1900);
      final dateB = b.weightDate ?? DateTime(1900);
      return dateB.compareTo(dateA);
    });

    for (var result in uniqueResults) {
      final weightValue = result.weightMeasured?.toDouble() ?? 0.0;
      final weightUnit = result.unit ?? unit;
      final date = result.weightDate;
      final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : '';
      final timeLabel = date != null ? _formatTime(date) : 'Unknown';
      final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown';
      final subTitleText = '${weightValue.toInt()} $weightUnit';

      listItems.add(
        Column(
          children: [
            buildHistoryListTile(
              title: displayLabel,
              subTitle: subTitleText,
              value: weightValue,
              measureDesc: '',
            ),
            Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h),
          ],
        ),
      );
    }
    return listItems;
  }

  Widget _buildLoadingShimmer({bool isForHistory = true}) {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.all(0.w),
      itemCount: 4,
      separatorBuilder: (_, __) => SizedBox(height: 12.h),
      itemBuilder: (context, index) {
        return Shimmer.fromColors(
          baseColor: AppColors.shimmerBaseColor,
          highlightColor: AppColors.shimmerHighlightColor,
          child: Container(
            height: isForHistory ? 60.h : 40.h,
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              borderRadius: BorderRadius.circular(10.r),
            ),
          ),
        );
      },
    );
  }

  Widget _buildEmptyStateWidget() {
    final isArabic = getIt.get<AppState>().isArabic();

    return SizedBox(
      height: MediaQuery.of(context).size.height * 0.5,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Utils.buildSvgWithAssets(
              icon: AppAssets.calendar,
              iconColor: AppColors.textColor,
              height: 48.w,
              width: 48.w,
            ),
            SizedBox(height: 16.h),
            (isArabic ? "ليس لديك أي بيانات متاحة." : "You do not have any data available.").toText14(
              weight: FontWeight.w600,
              color: AppColors.textColor,
              isCenter: true,
            ),
            SizedBox(height: 8.h),
            _getEmptyStateMessage().toText12(
              color: AppColors.greyTextColor,
              isCenter: true,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHistoryGraph() {
    return Consumer<HealthTrackersViewModel>(
      builder: (context, viewModel, _) {
        final selectedDuration = viewModel.selectedDurationFilter;
        List<DataPoint> dataPoints = [];
        List<DataPoint>? secondaryDataPoints;

        switch (widget.trackerType) {
          case HealthTrackerTypeEnum.bloodSugar:
            dataPoints = _buildBloodSugarGraphData(viewModel, selectedDuration);
            break;
          case HealthTrackerTypeEnum.bloodPressure:
            final (systolicData, diastolicData) = _buildBloodPressureGraphData(viewModel, selectedDuration);
            dataPoints = systolicData; // Systolic (primary line)
            secondaryDataPoints = diastolicData; // Diastolic (secondary line)
            break;
          case HealthTrackerTypeEnum.weightTracker:
            dataPoints = _buildWeightGraphData(viewModel, selectedDuration);
            break;
        }

        if (dataPoints.isEmpty) {
          return _buildEmptyStateWidget();
        }

        if (viewModel.isLoading) {
          return Container(
            padding: EdgeInsets.symmetric(vertical: 40.h),
            child: _buildLoadingShimmer(),
          );
        }

        // Calculate max value from both lines for blood pressure
        double maxDataValue = dataPoints.isNotEmpty ? dataPoints.map((p) => p.value).reduce((a, b) => a > b ? a : b) : 0.0;
        if (secondaryDataPoints != null && secondaryDataPoints.isNotEmpty) {
          final secondaryMax = secondaryDataPoints.map((p) => p.value).reduce((a, b) => a > b ? a : b);
          if (secondaryMax > maxDataValue) maxDataValue = secondaryMax;
        }

        double maxY = maxDataValue > 200 ? (maxDataValue * 1.2) : 250;
        double minY = 0;
        double horizontalInterval = maxY / 4;
        double leftLabelInterval = horizontalInterval;

        // Set colors based on tracker type
        Color graphColor = AppColors.successColor;
        Color? secondaryGraphColor;

        if (widget.trackerType == HealthTrackerTypeEnum.bloodPressure) {
          graphColor = AppColors.errorColor; // Red for Systolic
          secondaryGraphColor = AppColors.blueColor; // Blue for Diastolic
        }

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Legend for blood pressure
            if (widget.trackerType == HealthTrackerTypeEnum.bloodPressure) ...[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildLegendItem(AppColors.errorColor, LocaleKeys.systolic.tr()),
                  SizedBox(width: 24.w),
                  _buildLegendItem(AppColors.blueColor, LocaleKeys.diastolic.tr()),
                ],
              ),
              SizedBox(height: 12.h),
            ],
            CustomGraph(
              bottomLabelReservedSize: 30,
              dataPoints: dataPoints,
              secondaryDataPoints: secondaryDataPoints,
              makeGraphBasedOnActualValue: false,
              leftLabelReservedSize: 50.h,
              showGridLines: true,
              maxY: maxY,
              minY: minY,
              showLinePoints: true,
              maxX: dataPoints.length > 1 ? dataPoints.length.toDouble() - 0.75 : 1.0,
              horizontalInterval: horizontalInterval,
              leftLabelInterval: leftLabelInterval,
              showShadow: widget.trackerType != HealthTrackerTypeEnum.bloodPressure,
              graphColor: graphColor,
              secondaryGraphColor: secondaryGraphColor,
              graphShadowColor: graphColor.withValues(alpha: 0.15),
              getDrawingHorizontalLine: (value) {
                if (value % horizontalInterval == 0 && value > 0) {
                  return FlLine(
                    color: AppColors.greyTextColor.withValues(alpha: 0.3),
                    strokeWidth: 1.5,
                    dashArray: [8, 4],
                  );
                }
                return FlLine(color: AppColors.transparent, strokeWidth: 0);
              },
              leftLabelFormatter: (value) {
                final interval = maxY / 4;
                final positions = [0.0, interval, interval * 2, interval * 3, maxY];
                for (var position in positions) {
                  if ((value - position).abs() < 1) {
                    return '${value.toInt()}'.toText10(isBold: true);
                  }
                }
                return SizedBox.shrink();
              },
              bottomLabelFormatter: (value, data) {
                if (data.isEmpty) return SizedBox.shrink();
                if ((value - value.round()).abs() > 0.01) return SizedBox.shrink();
                int index = value.round();
                if (index < 0 || index >= data.length) return SizedBox.shrink();

                if (selectedDuration == 'Week' && index < 7) {
                  return Padding(
                    padding: EdgeInsets.only(top: 10.h),
                    child: data[index].label.toText10(isBold: true, color: AppColors.labelTextColor),
                  );
                }
                if (selectedDuration == 'Month' && index < 6) {
                  return Padding(
                    padding: EdgeInsets.only(top: 10.h),
                    child: data[index].label.toText10(isBold: true, color: AppColors.labelTextColor),
                  );
                }
                if (selectedDuration == 'Year' && index < 12) {
                  return Padding(
                    padding: EdgeInsets.only(top: 10.h),
                    child: data[index].label.toText8(isBold: true, color: AppColors.labelTextColor),
                  );
                }
                return SizedBox.shrink();
              },
              scrollDirection: selectedDuration == 'Year' ? Axis.horizontal : Axis.vertical,
              height: 250.h,
              spotColor: graphColor,
            ),
          ],
        );
      },
    );
  }

  /// Build legend item for graph
  Widget _buildLegendItem(Color color, String label) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 12.w,
          height: 12.w,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2.r),
          ),
        ),
        SizedBox(width: 6.w),
        label.toText12(isBold: true, color: AppColors.textColor),
      ],
    );
  }

  /// Build graph data for Blood Sugar
  List<DataPoint> _buildBloodSugarGraphData(HealthTrackersViewModel viewModel, String selectedDuration) {
    List<DataPoint> dataPoints = [];
    final unit = _getUnit();

    if (selectedDuration == 'Week') {
      final weekResults = viewModel.weekDiabeticResultAverage;
      if (weekResults.isNotEmpty) {
        final sortedResults = List<WeekDiabeticResultAverage>.from(weekResults);
        sortedResults.sort((a, b) => (a.dateChart ?? DateTime.now()).compareTo(b.dateChart ?? DateTime.now()));
        final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults;

        for (var result in last7Days) {
          final value = result.dailyAverageResult?.toDouble() ?? 0.0;
          final date = result.dateChart ?? DateTime.now();
          final label = _getDayName(date).substring(0, 3);
          dataPoints.add(DataPoint(
              value: value,
              label: label,
              actualValue: value.toStringAsFixed(1),
              time: date,
              displayTime: _getDayName(date),
              unitOfMeasurement: unit));
        }
      }
    } else if (selectedDuration == 'Month') {
      final monthResults = viewModel.monthDiabeticResultAverage;
      if (monthResults.isNotEmpty) {
        for (int i = 0; i < monthResults.length; i++) {
          final weekData = monthResults[i];
          final value = (weekData.weekAverageResult is num)
              ? (weekData.weekAverageResult as num).toDouble()
              : double.tryParse(weekData.weekAverageResult?.toString() ?? '0') ?? 0.0;
          final weekLabel = weekData.weekDesc ?? 'Week ${i + 1}';
          dataPoints.add(DataPoint(
              value: value,
              label: 'W${i + 1}',
              actualValue: value.toStringAsFixed(1),
              time: DateTime.now(),
              displayTime: weekLabel,
              unitOfMeasurement: unit));
        }
      }
    } else if (selectedDuration == 'Year') {
      final yearResults = viewModel.yearDiabeticResultAverage;
      if (yearResults.isNotEmpty) {
        for (int targetMonth = 1; targetMonth <= 12; targetMonth++) {
          final monthData = yearResults.firstWhere((m) => m.monthNumber == targetMonth,
              orElse: () => YearDiabeticResultAverage(monthAverageResult: 0.0, monthNumber: targetMonth, monthName: _getMonthName(targetMonth)));
          final value = monthData.monthAverageResult?.toDouble() ?? 0.0;
          final monthName = monthData.monthName ?? _getMonthName(targetMonth);
          final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName;
          dataPoints.add(DataPoint(
              value: value,
              label: label,
              actualValue: value.toStringAsFixed(1),
              time: DateTime(DateTime.now().year, targetMonth, 1),
              displayTime: monthName,
              unitOfMeasurement: unit));
        }
      }
    }
    return dataPoints;
  }

  /// Build graph data for Blood Pressure - returns (systolicData, diastolicData)
  (List<DataPoint>, List<DataPoint>) _buildBloodPressureGraphData(HealthTrackersViewModel viewModel, String selectedDuration) {
    List<DataPoint> systolicDataPoints = [];
    List<DataPoint> diastolicDataPoints = [];
    const unit = 'mmHg';

    if (selectedDuration == 'Week') {
      final weekResults = viewModel.weekBloodPressureResult;
      if (weekResults.isNotEmpty) {
        final sortedResults = List.from(weekResults);
        sortedResults.sort((a, b) => (a.bloodPressureDate ?? DateTime.now()).compareTo(b.bloodPressureDate ?? DateTime.now()));
        final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults;

        for (var result in last7Days) {
          final systolic = (result.systolicePressure ?? 0).toDouble();
          final diastolic = (result.diastolicPressure ?? 0).toDouble();
          final date = result.bloodPressureDate ?? DateTime.now();
          final label = _getDayName(date).substring(0, 3);

          systolicDataPoints.add(DataPoint(
              value: systolic,
              label: label,
              actualValue: '${systolic.toInt()}/${diastolic.toInt()}',
              time: date,
              displayTime: _getDayName(date),
              unitOfMeasurement: unit));

          diastolicDataPoints.add(DataPoint(
              value: diastolic,
              label: label,
              actualValue: diastolic.toStringAsFixed(0),
              time: date,
              displayTime: _getDayName(date),
              unitOfMeasurement: unit));
        }
      }
    } else if (selectedDuration == 'Month') {
      final monthResults = viewModel.monthBloodPressureResult;
      if (monthResults.isNotEmpty) {
        // Group by week and calculate averages
        final Map<String, List<dynamic>> weekGroups = {};
        for (var result in monthResults) {
          final weekDesc = result.weekDesc ?? 'Week 1';
          weekGroups.putIfAbsent(weekDesc, () => []);
          weekGroups[weekDesc]!.add(result);
        }

        int weekIndex = 0;
        for (var entry in weekGroups.entries) {
          final weekData = entry.value;
          double avgSystolic = 0;
          double avgDiastolic = 0;

          for (var result in weekData) {
            avgSystolic += (result.systolicePressure ?? 0);
            avgDiastolic += (result.diastolicPressure ?? 0);
          }

          if (weekData.isNotEmpty) {
            avgSystolic = avgSystolic / weekData.length;
            avgDiastolic = avgDiastolic / weekData.length;
          }

          final weekLabel = entry.key;
          systolicDataPoints.add(DataPoint(
              value: avgSystolic,
              label: 'W${weekIndex + 1}',
              actualValue: '${avgSystolic.toInt()}/${avgDiastolic.toInt()}',
              time: DateTime.now(),
              displayTime: weekLabel,
              unitOfMeasurement: unit));

          diastolicDataPoints.add(DataPoint(
              value: avgDiastolic,
              label: 'W${weekIndex + 1}',
              actualValue: avgDiastolic.toStringAsFixed(0),
              time: DateTime.now(),
              displayTime: weekLabel,
              unitOfMeasurement: unit));

          weekIndex++;
        }
      }
    } else if (selectedDuration == 'Year') {
      final yearResults = viewModel.yearBloodPressureResult;
      if (yearResults.isNotEmpty) {
        // Group by month and calculate averages
        final Map<int, List<dynamic>> monthGroups = {};
        for (var result in yearResults) {
          final chartMonth = result.chartMonth;
          final monthNum = _getMonthNumber(chartMonth ?? 'January');
          monthGroups.putIfAbsent(monthNum, () => []);
          monthGroups[monthNum]!.add(result);
        }

        for (int targetMonth = 1; targetMonth <= 12; targetMonth++) {
          double avgSystolic = 0;
          double avgDiastolic = 0;

          if (monthGroups.containsKey(targetMonth) && monthGroups[targetMonth]!.isNotEmpty) {
            final monthData = monthGroups[targetMonth]!;
            for (var result in monthData) {
              avgSystolic += (result.systolicePressure ?? 0);
              avgDiastolic += (result.diastolicPressure ?? 0);
            }
            avgSystolic = avgSystolic / monthData.length;
            avgDiastolic = avgDiastolic / monthData.length;
          }

          final monthName = _getMonthName(targetMonth);
          final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName;

          systolicDataPoints.add(DataPoint(
              value: avgSystolic,
              label: label,
              actualValue: '${avgSystolic.toInt()}/${avgDiastolic.toInt()}',
              time: DateTime(DateTime.now().year, targetMonth, 1),
              displayTime: monthName,
              unitOfMeasurement: unit));

          diastolicDataPoints.add(DataPoint(
              value: avgDiastolic,
              label: label,
              actualValue: avgDiastolic.toStringAsFixed(0),
              time: DateTime(DateTime.now().year, targetMonth, 1),
              displayTime: monthName,
              unitOfMeasurement: unit));
        }
      }
    }
    return (systolicDataPoints, diastolicDataPoints);
  }

  /// Helper to get month number from name
  int _getMonthNumber(String monthName) {
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    final index = months.indexWhere((m) => m.toLowerCase() == monthName.toLowerCase());
    return index >= 0 ? index + 1 : 1;
  }

  /// Build graph data for Weight
  List<DataPoint> _buildWeightGraphData(HealthTrackersViewModel viewModel, String selectedDuration) {
    List<DataPoint> dataPoints = [];
    final unit = _getUnit();

    if (selectedDuration == 'Week') {
      final weekResults = viewModel.weekWeightMeasurementResultAverage;
      if (weekResults.isNotEmpty) {
        final sortedResults = List<WeekWeightMeasurementResultAverage>.from(weekResults);
        sortedResults.sort((a, b) => (a.weightDate ?? DateTime.now()).compareTo(b.weightDate ?? DateTime.now()));
        final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults;

        for (var result in last7Days) {
          final value = result.dailyAverageResult?.toDouble() ?? 0.0;
          final date = result.weightDate ?? DateTime.now();
          final label = _getDayName(date).substring(0, 3);
          dataPoints.add(DataPoint(
              value: value,
              label: label,
              actualValue: value.toStringAsFixed(1),
              time: date,
              displayTime: _getDayName(date),
              unitOfMeasurement: unit));
        }
      }
    } else if (selectedDuration == 'Month') {
      final monthResults = viewModel.monthWeightMeasurementResultAverage;
      if (monthResults.isNotEmpty) {
        for (int i = 0; i < monthResults.length; i++) {
          final weekData = monthResults[i];
          final value = weekData.weekAverageResult?.toDouble() ?? 0.0;
          final weekLabel = weekData.weekDesc ?? 'Week ${i + 1}';
          dataPoints.add(DataPoint(
              value: value,
              label: 'W${i + 1}',
              actualValue: value.toStringAsFixed(1),
              time: DateTime.now(),
              displayTime: weekLabel,
              unitOfMeasurement: unit));
        }
      }
    } else if (selectedDuration == 'Year') {
      final yearResults = viewModel.yearWeightMeasurementResultAverage;
      if (yearResults.isNotEmpty) {
        for (int targetMonth = 1; targetMonth <= 12; targetMonth++) {
          final monthData = yearResults.firstWhere((m) => m.monthNumber == targetMonth,
              orElse: () =>
                  YearWeightMeasurementResultAverage(monthAverageResult: 0.0, monthNumber: targetMonth, monthName: _getMonthName(targetMonth)));
          final value = monthData.monthAverageResult?.toDouble() ?? 0.0;
          final monthName = monthData.monthName ?? _getMonthName(targetMonth);
          final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName;
          dataPoints.add(DataPoint(
              value: value,
              label: label,
              actualValue: value.toStringAsFixed(1),
              time: DateTime(DateTime.now().year, targetMonth, 1),
              displayTime: monthName,
              unitOfMeasurement: unit));
        }
      }
    }
    return dataPoints;
  }

  void onSendEmailPressed(BuildContext context) async {
    _showEmailInputBottomSheet(context);
  }

  /// Show email input bottom sheet
  void _showEmailInputBottomSheet(BuildContext context) {
    final viewModel = context.read<HealthTrackersViewModel>();
    final appState = getIt.get<AppState>();
    final dialogService = getIt.get<DialogService>();

    // Get user's email from authenticated user
    final userEmail = appState.getAuthenticatedUser()?.emailAddress ?? '';

    // Create email controller and pre-fill if available
    final emailController = TextEditingController(text: userEmail);

    dialogService.showFamilyBottomSheetWithoutHWithChild(
      label: LocaleKeys.sendReportByEmail.tr(),
      message: "",
      child: _buildEmailInputContent(
        context: context,
        emailController: emailController,
        viewModel: viewModel,
        dialogService: dialogService,
      ),
      onOkPressed: () {},
    );
  }

  /// Build email input content
  Widget _buildEmailInputContent({
    required BuildContext context,
    required TextEditingController emailController,
    required HealthTrackersViewModel viewModel,
    required DialogService dialogService,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        LocaleKeys.enterYourEmailToReceiveReport.tr().toText14(
              color: AppColors.textColor,
              weight: FontWeight.w400,
            ),
        SizedBox(height: 16.h),

        // Email Input Field using TextInputWidget
        TextInputWidget(
          padding: EdgeInsets.symmetric(horizontal: 8.w),
          labelText: LocaleKeys.email.tr(context: context),
          hintText: LocaleKeys.enterEmail.tr(context: context),
          controller: emailController,
          keyboardType: TextInputType.emailAddress,
          isEnable: true,
          isBorderAllowed: true,
          isAllowRadius: true,
        ),

        SizedBox(height: 24.h),

        // Send Button
        Row(
          children: [
            Expanded(
              child: CustomButton(
                height: 56.h,
                text: LocaleKeys.send.tr(context: context),
                onPressed: () {
                  _sendEmailReport(
                    context: context,
                    email: emailController.text.trim(),
                    viewModel: viewModel,
                    dialogService: dialogService,
                  );
                },
                textColor: AppColors.whiteColor,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// Send email report based on tracker type
  Future<void> _sendEmailReport({
    required BuildContext context,
    required String email,
    required HealthTrackersViewModel viewModel,
    required DialogService dialogService,
  }) async {
    // Validate email
    if (email.isEmpty) {
      dialogService.showErrorBottomSheet(
        message: LocaleKeys.enterEmail.tr(context: context),
      );
      return;
    }

    // Basic email validation
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegex.hasMatch(email)) {
      dialogService.showErrorBottomSheet(
        message: LocaleKeys.pleaseEnterAValidEmail.tr(context: context),
      );
      return;
    }

    // Close the email input bottom sheet
    Navigator.of(context).pop();

    // Call appropriate email function based on tracker type
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));
        await viewModel.sendBloodSugarReportByEmail(
          email: email,
          onSuccess: () {
            LoaderBottomSheet.hideLoader();

            _showSuccessMessage(context, dialogService);
          },
          onFailure: (error) {
            LoaderBottomSheet.hideLoader();
            dialogService.showErrorBottomSheet(message: error);
          },
        );
        break;

      case HealthTrackerTypeEnum.bloodPressure:
        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));

        await viewModel.sendBloodPressureReportByEmail(
          email: email,
          onSuccess: () {
            LoaderBottomSheet.hideLoader();

            _showSuccessMessage(context, dialogService);
          },
          onFailure: (error) {
            LoaderBottomSheet.hideLoader();

            dialogService.showErrorBottomSheet(message: error);
          },
        );
        break;

      case HealthTrackerTypeEnum.weightTracker:
        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));
        await viewModel.sendWeightReportByEmail(
          email: email,
          onSuccess: () {
            LoaderBottomSheet.hideLoader();

            _showSuccessMessage(context, dialogService);
          },
          onFailure: (error) {
            LoaderBottomSheet.hideLoader();

            dialogService.showErrorBottomSheet(message: error);
          },
        );
        break;
    }
  }

  /// Show success message
  void _showSuccessMessage(BuildContext context, DialogService dialogService) {
    showCommonBottomSheetWithoutHeight(
      context,
      child: Utils.getSuccessWidget(
        loadingText: LocaleKeys.emailSentSuccessfully.tr(context: context),
      ),
      callBackFunc: () {},
      isCloseButtonVisible: false,
      isDismissible: true,
      isFullScreen: false,
    );
  }

  Widget _buildPageShimmer() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        children: [
          SizedBox(height: 16.h),
          Shimmer.fromColors(
            baseColor: AppColors.shimmerBaseColor,
            highlightColor: AppColors.shimmerHighlightColor,
            child: Container(
              height: 120.h,
              decoration: BoxDecoration(
                color: AppColors.whiteColor,
                borderRadius: BorderRadius.circular(24.r),
              ),
            ),
          ),
          SizedBox(height: 16.h),
          Shimmer.fromColors(
            baseColor: AppColors.shimmerBaseColor,
            highlightColor: AppColors.shimmerHighlightColor,
            child: Container(
              height: 300.h,
              decoration: BoxDecoration(
                color: AppColors.whiteColor,
                borderRadius: BorderRadius.circular(24.r),
              ),
            ),
          ),
          SizedBox(height: 16.h),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        downloadReport: () async {



          await context.read<HealthTrackersViewModel>().downloadReport(widget.trackerType,
              onSuccess: (report) async {

                if (report.isEmpty) {}
                String path = await Utils.createFileFromString(report, "pdf");
                try {
                  OpenFilex.open(path);
                } catch (ex) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: "Cannot open file"),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                }
              });



              // .downloadBloodSugerReport();
        },
        title: _getPageTitle(),
        bottomChild: Consumer<HealthTrackersViewModel>(
          builder: (context, viewModel, child) {
            return Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.r,
                hasShadow: true,
              ),
              child: Padding(
                padding: EdgeInsets.all(24.w),
                child: CustomButton(
                  text: LocaleKeys.addNewRecord.tr(),
                  onPressed: () {
                    if (!viewModel.isLoading) {
                      context.navigateWithName(AppRoutes.addHealthTrackerEntryPage, arguments: widget.trackerType);
                    }
                  },
                  icon: AppAssets.add_icon,
                  borderRadius: 12.r,
                  borderColor: AppColors.transparent,
                  padding: EdgeInsets.symmetric(vertical: 14.h),
                ),
              ),
            );
          },
        ),
        child: Consumer<HealthTrackersViewModel>(
          builder: (context, viewModel, child) {
            if (viewModel.isLoading) {
              return _buildPageShimmer();
            }

            if (_hasNoData(viewModel)) {
              return _buildEmptyStateWidget();
            }

            return Column(
              children: [
                SizedBox(height: 16.h),
                TrackerLastValueCard(trackerType: widget.trackerType),
                SizedBox(height: 16.h),
                _buildHistoryGraphOrList(),
                SizedBox(height: 16.h),
              ],
            );
          },
        ),
      ),
    );
  }
}
