import 'dart:ui';

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_state.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/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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/vital_sign_ui_model.dart';
import 'package:hmg_patient_app_new/presentation/vital_sign/vital_sign_details_page.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class VitalSignPage extends StatefulWidget {
  const VitalSignPage({super.key});

  @override
  State<VitalSignPage> createState() => _VitalSignPageState();
}

class _VitalSignPageState extends State<VitalSignPage> {

  // Helper function to check if a value is valid (not null, not 0, not empty string)
  bool _isValidValue(dynamic value) {
    if (value == null) return false;
    if (value is num) return value > 0;
    if (value is String) {
      if (value.trim().isEmpty) return false;
      final parsed = double.tryParse(value);
      return parsed != null && parsed > 0;
    }
    return false;
  }

  // Helper function to format vital sign values, showing '--' instead of 0 or null
  String _formatValue(dynamic value) {
    if (value == null) return '--';
    if (value is num && value == 0) return '--';
    if (value is String) {
      if (value.trim().isEmpty) return '--';
      final parsed = double.tryParse(value);
      if (parsed == null || parsed == 0) return '--';
    }
    return value.toString();
  }

  void _openDetails(VitalSignDetailsArgs args) {
    Navigator.of(context).push(
      CustomPageRoute(
        page: VitalSignDetailsPage(args: args),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.vitalSigns.tr(context: context),
        child: Consumer<HmgServicesViewModel>(
          builder: (context, viewModel, child) {

            // Get the latest vital sign data (first item in the list)
            VitalSignResModel? latestVitalSign = viewModel.vitalSignList.isNotEmpty
                ? viewModel.vitalSignList.first
                : null;

            // Debug logging for blood pressure
            // if (latestVitalSign != null) {
            //   print('=== Blood Pressure Debug ===');
            //   print('bloodPressureHigher: ${latestVitalSign.bloodPressureHigher}');
            //   print('bloodPressureLower: ${latestVitalSign.bloodPressureLower}');
            //   print('bloodPressureHigher type: ${latestVitalSign.bloodPressureHigher.runtimeType}');
            //   print('bloodPressureLower type: ${latestVitalSign.bloodPressureLower.runtimeType}');
            //   print('bloodPressureHigher == 0: ${latestVitalSign.bloodPressureHigher == 0}');
            //   print('bloodPressureLower == 0: ${latestVitalSign.bloodPressureLower == 0}');
            //   print('========================');
            // }

            return SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 16.h),

                  // Main content with body image
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24.h),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Left side - Vital Sign Cards
                        Expanded(
                          child: Column(
                            children: [
                              // BMI Card
                              _buildVitalSignCard(
                                icon: AppAssets.bmiVital,
                                label: LocaleKeys.bmi.tr(context: context),
                                value: _formatValue(latestVitalSign?.bodyMassIndex),
                                unit: '',
                                status: VitalSignUiModel.bmiStatus(latestVitalSign?.bodyMassIndex),
                                onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.bmi,
                                    title: LocaleKeys.bmi.tr(context: context),
                                    icon: AppAssets.bmiVital,
                                    unit: '',
                                  ),
                                ),
                              ),
                              SizedBox(height: 16.h),

                              // Height Card
                              _buildVitalSignCard(
                                icon: AppAssets.heightVital,
                                label: LocaleKeys.height.tr(context: context),
                                value: _formatValue(latestVitalSign?.heightCm),
                                unit: 'cm',
                                status: null,
                                onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.height,
                                    title: LocaleKeys.height.tr(context: context),
                                    icon: AppAssets.heightVital,
                                    unit: 'cm',
                                  ),
                                ),
                              ),
                              SizedBox(height: 16.h),

                              // Weight Card
                              _buildVitalSignCard(
                                icon: AppAssets.weightVital,
                                label: LocaleKeys.weight.tr(context: context),
                                value: _formatValue(latestVitalSign?.weightKg),
                                unit: 'kg',
                                status: (latestVitalSign?.weightKg != null)
                                    ? VitalSignUiModel.weightStatus(latestVitalSign?.bodyMassIndex)
                                    : null,
                                onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.weight,
                                    title: LocaleKeys.weight.tr(context: context),
                                    icon: AppAssets.weightVital,
                                    unit: 'kg',
                                  ),
                                ),
                              ),
                              SizedBox(height: 16.h),

                              // Blood Pressure Card
                              _buildVitalSignCard(
                                icon: AppAssets.bloodPressure,
                                label: LocaleKeys.bloodPressure.tr(context: context),
                                value: (latestVitalSign != null &&
                                        _isValidValue(latestVitalSign.bloodPressureHigher) &&
                                        _isValidValue(latestVitalSign.bloodPressureLower))
                                    ? '${latestVitalSign.bloodPressureHigher}/${latestVitalSign.bloodPressureLower}'
                                    : '--',
                                unit: '',
                                status: (latestVitalSign != null &&
                                        _isValidValue(latestVitalSign.bloodPressureHigher) &&
                                        _isValidValue(latestVitalSign.bloodPressureLower))
                                    ? VitalSignUiModel.bloodPressureStatus(
                                        systolic: latestVitalSign.bloodPressureHigher,
                                        diastolic: latestVitalSign.bloodPressureLower,
                                      )
                                    : null,
                                onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.bloodPressure,
                                    title: LocaleKeys.bloodPressure.tr(context: context),
                                    icon: AppAssets.bloodPressure,
                                    unit: 'mmHg',
                                    low: 90,
                                    high: 140,
                                  ),
                                ),
                              ),
                              SizedBox(height: 16.h),

                              // Temperature Card
                              _buildVitalSignCard(
                                icon: AppAssets.temperature,
                                label: LocaleKeys.temperature.tr(context: context),
                                value: _formatValue(latestVitalSign?.temperatureCelcius),
                                unit: '°C',
                                status: null,
                                onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.temperature,
                                    title: LocaleKeys.temperature.tr(context: context),
                                    icon: AppAssets.temperature,
                                    unit: '°C',
                                    low: 36.1,
                                    high: 37.2,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                        SizedBox(width: 16.h),

                        // Right side - Body Image and Heart Rate + Respiratory Rate
                        Expanded(
                          child: Column(
                            children: [
                              // Body anatomy image with Heart Rate card overlaid at bottom
                              SizedBox(
                                height: 420.h,
                                width: double.infinity,
                                child: Stack(
                                  clipBehavior: Clip.none,
                                  children: [
                                    // Image
                                    Positioned.fill(
                                      child: Stack(
                                        fit: StackFit.expand,
                                        children: [
                                          Utils.buildImgWithAssets(
                                            icon: getIt.get<AppState>().getAuthenticatedUser()?.gender == 1
                                                ? AppAssets.bmiFullBody
                                                : AppAssets.bmiFullBodyFemale,
                                            fit: BoxFit.cover,
                                          ),
                                          Align(
                                            alignment: Alignment.bottomCenter,
                                            child: SizedBox(
                                              height: 460.h,
                                              child: ImageFiltered(
                                                imageFilter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    gradient: LinearGradient(
                                                      begin: Alignment.topCenter,
                                                      end: Alignment.bottomCenter,
                                                      colors: [
                                                        AppColors.whiteColor.withValues(alpha: 0.0),
                                                        AppColors.whiteColor.withValues(alpha: 0.97),
                                                        AppColors.whiteColor,
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

                                    // Overlay Heart Rate card
                                    Positioned(
                                      left: 0,
                                      right: 0,
                                      bottom: 12.h,
                                      child: _buildVitalSignCard(
                                        icon: AppAssets.heart,
                                        label: LocaleKeys.heart.tr(context: context),
                                        value: _formatValue(latestVitalSign?.heartRate ?? latestVitalSign?.pulseBeatPerMinute),
                                        unit: 'bpm',
                                        status: _isValidValue(latestVitalSign?.heartRate ?? latestVitalSign?.pulseBeatPerMinute) ? VitalSignStatus.normal : null,
                                        onTap: () => _openDetails(
                                          VitalSignDetailsArgs(
                                            metric: VitalSignMetric.heartRate,
                                            title: LocaleKeys.heart.tr(context: context),
                                            icon: AppAssets.heart,
                                            unit: 'bpm',
                                            low: 60,
                                            high: 100,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                               SizedBox(height: 12.h),

                               // Respiratory rate Card
                               _buildVitalSignCard(
                                 icon: AppAssets.respRate,
                                label: LocaleKeys.respirationRate.tr(context: context),
                                value: _formatValue(latestVitalSign?.respirationBeatPerMinute),
                                 unit: 'bpm',
                                 status: _isValidValue(latestVitalSign?.respirationBeatPerMinute) ? VitalSignStatus.normal : null,
                                 onTap: () => _openDetails(
                                  VitalSignDetailsArgs(
                                    metric: VitalSignMetric.respiratoryRate,
                                    title: LocaleKeys.respirationRate.tr(context: context),
                                    icon: AppAssets.respRate,
                                     unit: 'bpm',
                                     low: 12,
                                     high: 20,
                                   ),
                                 ),
                               ),
                             ],
                           ),
                         ),
                      ],
                    ),
                  ),

                  SizedBox(height: 60.h),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildVitalSignCard({
    required String icon,
    required String label,
    required String value,
    required String unit,
    required VitalSignStatus? status,
    required VoidCallback onTap,
  }) {
    final VitalSignUiModel scheme = VitalSignUiModel.scheme(status: status, label: label);

    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          borderRadius: 16.r,
          hasShadow: false,
        ),
        child: Padding(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    padding: EdgeInsets.all(8.h),
                    decoration: BoxDecoration(
                      color: scheme.iconBg,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Utils.buildSvgWithAssets(
                      icon: icon,
                      width: 22.w,
                      height: 22.h,
                      iconColor: scheme.iconFg,
                      fit: BoxFit.contain,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  Expanded(
                    child: label.toText14(
                      color: AppColors.textColor,
                      weight: FontWeight.w600,
                    ),
                  ),
                  Utils.buildSvgWithAssets(
                    icon: getIt.get<AppState>().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward,
                      width: 18.w, height: 18.h),
                ],
              ),
              SizedBox(height: 14.h),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                // decoration: BoxDecoration(
                //   color: AppColors.bgScaffoldColor,
                //   borderRadius: BorderRadius.circular(10.r),
                // ),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.bgScaffoldColor,
                  borderRadius: 10.r,
                  hasShadow: false,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        value.toText17(
                          isBold: true,
                          color: AppColors.textColor,
                          isEnglishOnly: true
                        ),
                        if (unit.isNotEmpty && value != '--' && value != '0') ...[
                          SizedBox(width: 3.w),
                          unit.toText12(
                            color: AppColors.textColor,
                            isBold: true,
                          ),
                        ],
                      ],
                    ),
                    if (status != null)
                      AppCustomChipWidget(
                        labelText: VitalSignUiModel.statusToString(status),
                        backgroundColor: scheme.chipBg,
                        textColor: scheme.chipFg,

                      )
                    else
                      const SizedBox.shrink(),
                  ],
                ),
              ),
              // SizedBox(height: 8.h),
              // Align(
              //   alignment: AlignmentDirectional.centerEnd,
              //   child: Utils.buildSvgWithAssets(
              //     icon: AppAssets.arrow_forward,
              //     width: 18.w,
              //     height: 18.h,
              //     iconColor: AppColors.textColorLight,
              //     fit: BoxFit.contain,
              //   ),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}
