import 'package:easy_localization/easy_localization.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/enums.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.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/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/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class TrackerLastValueCard extends StatelessWidget {
  final HealthTrackerTypeEnum trackerType;

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

  /// Get status text and color based on blood sugar value
  (String status, Color color, Color bgColor) _getBloodSugarStatus(double value) {
    if (value < 70) {
      return (LocaleKeys.low.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.5));
    } else if (value <= 100) {
      return (LocaleKeys.normal.tr(), AppColors.successColor, AppColors.successLightBgColor);
    } else if (value <= 125) {
      return (LocaleKeys.preDiabetic.tr(), AppColors.ratingColorYellow, AppColors.errorColor.withValues(alpha: 0.4));
    } else {
      return (LocaleKeys.high.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.4));
    }
  }

  /// Get status text and color based on blood pressure value (systolic)
  (String status, Color color, Color bgColor) _getBloodPressureStatus(int systolic) {
    if (systolic < 90) {
      return (LocaleKeys.low.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.5));
    } else if (systolic <= 120) {
      return (LocaleKeys.normal.tr(), AppColors.successColor, AppColors.successLightBgColor);
    } else if (systolic <= 140) {
      return (LocaleKeys.elevated.tr(), AppColors.ratingColorYellow, AppColors.errorColor.withValues(alpha: 0.4));
    } else {
      return (LocaleKeys.high.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.4));
    }
  }

  /// Get status for weight (neutral - no good/bad status)
  (String status, Color color, Color bgColor) _getWeightStatus() {
    return (LocaleKeys.recorded.tr(), AppColors.successColor, AppColors.successLightBgColor);
  }

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

  @override
  Widget build(BuildContext context) {
    return Consumer<HealthTrackersViewModel>(
      builder: (context, viewModel, child) {
        // Get the last record based on tracker type
        dynamic lastRecord;
        String displayValue = '--';
        String unit = _getDefaultUnit();
        DateTime? lastDate;
        String status = '';
        Color statusColor = AppColors.greyTextColor;

        switch (trackerType) {
          case HealthTrackerTypeEnum.bloodSugar:
            final allResults = [
              ...viewModel.weekDiabeticPatientResult,
              ...viewModel.monthDiabeticPatientResult,
              ...viewModel.yearDiabeticPatientResult,
            ];
            if (allResults.isNotEmpty) {
              allResults.sort((a, b) {
                final dateA = a.dateChart ?? DateTime(1900);
                final dateB = b.dateChart ?? DateTime(1900);
                return dateB.compareTo(dateA);
              });
              lastRecord = allResults.first;
              final lastValue = lastRecord.resultValue?.toDouble() ?? 0.0;
              displayValue = lastValue.toStringAsFixed(0);
              unit = lastRecord.unit ?? 'mg/dL';
              lastDate = lastRecord.dateChart;
              final (s, c, _) = _getBloodSugarStatus(lastValue);
              status = s;
              statusColor = c;
            }
            break;

          case HealthTrackerTypeEnum.bloodPressure:
            final allResults = [
              ...viewModel.weekBloodPressureResult,
              ...viewModel.monthBloodPressureResult,
              ...viewModel.yearBloodPressureResult,
            ];
            if (allResults.isNotEmpty) {
              allResults.sort((a, b) {
                final dateA = a.bloodPressureDate ?? DateTime(1900);
                final dateB = b.bloodPressureDate ?? DateTime(1900);
                return dateB.compareTo(dateA);
              });
              lastRecord = allResults.first;
              final systolic = lastRecord.systolicePressure ?? 0;
              final diastolic = lastRecord.diastolicPressure ?? 0;
              displayValue = '$systolic/$diastolic';
              unit = 'mmHg';
              lastDate = lastRecord.bloodPressureDate;
              final (s, c, _) = _getBloodPressureStatus(systolic);
              status = s;
              statusColor = c;
            }
            break;

          case HealthTrackerTypeEnum.weightTracker:
            final allResults = [
              ...viewModel.weekWeightMeasurementResult,
              ...viewModel.monthWeightMeasurementResult,
              ...viewModel.yearWeightMeasurementResult,
            ];
            if (allResults.isNotEmpty) {
              allResults.sort((a, b) {
                final dateA = a.weightDate ?? DateTime(1900);
                final dateB = b.weightDate ?? DateTime(1900);
                return dateB.compareTo(dateA);
              });
              lastRecord = allResults.first;
              final weightValue = lastRecord.weightMeasured?.toDouble() ?? 0.0;
              displayValue = weightValue.toStringAsFixed(0);
              unit = lastRecord.unit ?? 'kg';
              lastDate = lastRecord.weightDate;
              final (s, c, _) = _getWeightStatus();
              status = s;
              statusColor = c;
            }
            break;
        }

        // final formattedDate = lastDate != null ? DateFormat('EE DD MMM, yy').format(lastDate) : DateFormat('EE DD MMM, yy').format(DateTime.now());
        final formattedDate = lastDate != null
            ? DateUtil.getWeekDayMonthDayYearDateFormatted(
                lastDate,
                "en",
              )
            : DateUtil.getWeekDayMonthDayYearDateFormatted(
                DateTime.now(),
                "en",
              );

        // Show shimmer while loading
        if (viewModel.isLoading) {
          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: Shimmer.fromColors(
              baseColor: AppColors.shimmerBaseColor,
              highlightColor: AppColors.shimmerHighlightColor,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 40.h,
                    width: 120.w,
                    decoration: BoxDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Row(
                    children: [
                      Container(
                        height: 32.h,
                        width: 150.w,
                        decoration: BoxDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Container(
                        height: 32.h,
                        width: 80.w,
                        decoration: BoxDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
        }

        // Show empty state if no records
        if (lastRecord == null) {
          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: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    "--".toText32(isBold: true, color: AppColors.greyTextColor),
                    SizedBox(width: 6.w),
                    unit.toText12(color: AppColors.greyTextColor, isBold: true).paddingOnly(top: 8.h),
                  ],
                ),
                SizedBox(height: 8.h),
                AppCustomChipWidget(
                  labelText: LocaleKeys.noRecordsYet.tr(),
                  icon: AppAssets.doctor_calendar_icon,
                ),
              ],
            ),
          );
        }

        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: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  displayValue.toText32(isBold: true, color: statusColor),
                  SizedBox(width: 6.w),
                  unit.toText12(color: AppColors.greyTextColor, isBold: true).paddingOnly(top: 8.h),
                ],
              ),
              SizedBox(height: 8.h),
              Row(
                children: [
                  AppCustomChipWidget(
                    labelText: "${LocaleKeys.lastRecord.tr()}: $formattedDate",
                    icon: AppAssets.doctor_calendar_icon,
                  ),
                  SizedBox(width: 8.w),
                  if (trackerType != HealthTrackerTypeEnum.weightTracker) ...[
                    AppCustomChipWidget(
                      labelText: status,
                      icon: AppAssets.normalStatusGreenIcon,
                      iconColor: statusColor,
                    ),
                  ]
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}
