import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/core/app_assets.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/services/dialog_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart';

import '../../../generated/locale_keys.g.dart';

class BMIWidget extends StatefulWidget {
  Function(dynamic result)? onChange;

  BMIWidget({super.key, required this.onChange});

  @override
  _BMIWidgetState createState() => _BMIWidgetState();
}

class _BMIWidgetState extends State<BMIWidget> {
  final TextEditingController _heightController = TextEditingController();
  final TextEditingController _weightController = TextEditingController();
  // Map keys are the localization keys (when available) or plain strings.
  // Map values are the actual unit values used for calculations.
  final Map<String, String> _heightUnitsMap = {
    LocaleKeys.cm: 'cm',
    LocaleKeys.m: 'm', // no LocaleKeys entry found for meter, fallback to key 'm'
    LocaleKeys.ft: 'ft',
    LocaleKeys.inch: 'in', // no LocaleKeys entry for inches, fallback
  };

  final Map<String, String> _weightUnitsMap = {
    LocaleKeys.kg: 'kg',
    LocaleKeys.lb: 'lb',
  };
  String selectedHeightUnit = 'cm';
  String selectedWeightUnit = 'kg';

  // Helper to return a localized label for a given selected (value) unit.
  String _getUnitLabel(Map<String, String> map, String value) {
    final entry = map.entries.firstWhere((e) => e.value == value, orElse: () => MapEntry(value, value));
    // tr() will return the localized string if available, otherwise it will return the key itself.
    return entry.key.tr(context: context);
  }

  @override
  void initState() {
    super.initState();
    _heightController.addListener(_onInputChanged);
    _weightController.addListener(_onInputChanged);
  }

  @override
  void dispose() {
    _heightController.removeListener(_onInputChanged);
    _weightController.removeListener(_onInputChanged);
    _heightController.dispose();
    _weightController.dispose();
    super.dispose();
  }

  void _onInputChanged() {
    final provider = Provider.of<HealthCalcualtorViewModel>(context, listen: false);
    provider.calculateBMI(heightText: _heightController.text, weightText: _weightController.text, heightUnit: selectedHeightUnit, weightUnit: selectedWeightUnit);
    // notify parent
    if (widget.onChange != null) widget.onChange!(provider.bmiResultMap);
  }

  @override
  Widget build(BuildContext context) {
    DialogService dialogService = getIt<DialogService>();

    return Consumer<HealthCalcualtorViewModel>(builder: (context, provider, _) {
      return Container(
        margin: EdgeInsets.zero,
        padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h),
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.height, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      LocaleKeys.height.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _heightController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '175',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black87, height: 1.0),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  width: 1.w,
                  height: 30.w,
                  color: Color(0xFFEAEAEB),
                ).paddingOnly(right: 10.w),
                Expanded(
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          LocaleKeys.unit.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          // Show localized label for the currently selected height unit
                          _getUnitLabel(_heightUnitsMap, selectedHeightUnit).toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    dialogService.showFamilyBottomSheetWithoutHWithChild(
                      label: LocaleKeys.unit.tr(context: context),
                      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: _heightUnitsMap.length,
                          itemBuilder: (context, index) {
                            final entry = _heightUnitsMap.entries.elementAt(index);
                            final key = entry.key;
                            final value = entry.value;
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SizedBox(
                                  height: 70,
                                  child: Row(
                                    spacing: 8.h,
                                    children: [
                                      Radio<String>(
                                        value: value,
                                        groupValue: selectedHeightUnit,
                                        activeColor: AppColors.errorColor,
                                        onChanged: (String? value) {
                                          if (value == null) return;
                                          setState(() {
                                            selectedHeightUnit = value;
                                            _onInputChanged();
                                          });
                                          Navigator.pop(context);
                                        },
                                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                      ),
                                      // show localized label (if available) otherwise show the key itself
                                      key.tr(context: context).toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                                    ],
                                  ).onPress(() {
                                    setState(() {
                                      selectedHeightUnit = value;
                                    });
                                    Navigator.pop(context);
                                  }),
                                ),
                              ],
                            );
                          },
                          separatorBuilder: (BuildContext context, int index) {
                            return Divider(height: 1, color: Color(0xFFEEEEEE));
                          },
                        ),
                      ),
                      onOkPressed: () {},
                    );
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.weight, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      LocaleKeys.weight.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _weightController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '75',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                            height: 1.0,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  width: 1.w,
                  height: 30.w,
                  color: Color(0xFFEAEAEB),
                ).paddingOnly(right: 10.w),
                Expanded(
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          LocaleKeys.unit.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          // Show localized label for the currently selected weight unit
                          _getUnitLabel(_weightUnitsMap, selectedWeightUnit).toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    dialogService.showFamilyBottomSheetWithoutHWithChild(
                      label: LocaleKeys.unit.tr(context: context),
                      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: _weightUnitsMap.length,
                          itemBuilder: (context, index) {
                            final entry = _weightUnitsMap.entries.elementAt(index);
                            final key = entry.key;
                            final value = entry.value;
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SizedBox(
                                  height: 70,
                                  child: Row(
                                    spacing: 8.h,
                                    children: [
                                      Radio<String>(
                                        value: value,
                                        groupValue: selectedWeightUnit,
                                        activeColor: AppColors.errorColor,
                                        onChanged: (String? value) {
                                          if (value == null) return;
                                          setState(() {
                                            selectedWeightUnit = value;
                                          });
                                          Navigator.pop(context);
                                        },
                                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                      ),
                                      key.tr(context: context).toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                                    ],
                                  ).onPress(() {
                                    setState(() {
                                      selectedWeightUnit = value;
                                      _onInputChanged();
                                    });
                                    Navigator.pop(context);
                                  }),
                                ),
                              ],
                            );
                          },
                          separatorBuilder: (BuildContext context, int index) {
                            return Divider(height: 1, color: Color(0xFFEEEEEE));
                          },
                        ),
                      ),
                      onOkPressed: () {},
                    );
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.globe, width: 18.w, height: 18.w),
                SizedBox(width: 12.w),
                Expanded(
                  child: "Calculate the BMI value and weight status to identify the healthy weight. NOt appropriate for children and women who are pregnant or breastfeeding."
                      .toText12(isBold: true, color: AppColors.inputLabelTextColor),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
          ],
        ),
      );
    });
  }
}
