import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:provider/provider.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/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';

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

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

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

class _CaloriesWidgetState extends State<CaloriesWidget> {
  final TextEditingController _heightController = TextEditingController();
  final TextEditingController _weightController = TextEditingController();
  final TextEditingController _ageController = TextEditingController();

  final Map<String, String> _heightUnits = {
    'cm': LocaleKeys.cm,
    'm': LocaleKeys.m,
    'ft': LocaleKeys.ft,
    'in': LocaleKeys.inch,
  };

  final Map<String, String> _weightUnits = {
    'kg': LocaleKeys.kg,
    'lb': LocaleKeys.lb,
  };

  final Map<String, String> _genders = {
    'Male': LocaleKeys.malE,
    'Female': LocaleKeys.femaleGender,
  };

  final Map<String, String> _activityLevels = {
    'Almost Inactive (no exercise)': LocaleKeys.almostInactive,
    'Lightly active': LocaleKeys.lightlyActive,
    'Lightly active (1-3) days per week': LocaleKeys.lightlyActive13Days,
    'Super active (very hard exercise)': LocaleKeys.superActive,
  };

  String selectedHeightUnit = 'cm';
  String selectedWeightUnit = 'kg';
  String selectedActivityLevel = 'Lightly active';
  String selectedGender = "Male";

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

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

  void _onInputChanged() {
    final provider = Provider.of<HealthCalcualtorViewModel>(context, listen: false);
    provider.calculateBMRAndCalories(
      heightText: _heightController.text,
      weightText: _weightController.text,
      ageText: _ageController.text,
      heightUnit: selectedHeightUnit,
      weightUnit: selectedWeightUnit,
      gender: selectedGender,
      activityLevel: selectedActivityLevel,
    );
    if (widget.onChange != null) widget.onChange!(provider.caloriesResultMap);
  }

  @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: [
            // === GENDER ROW ===
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.gender, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          LocaleKeys.selectGender.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          (_genders[selectedGender] ?? selectedGender).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                    ],
                  ),
                ),
                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down),
                SizedBox(width: 4.w),
              ],
            ).paddingSymmetrical(0.w, 16.w).onPress(() {
              dialogService.showFamilyBottomSheetWithoutHWithChild(
                label: LocaleKeys.selectGender.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: _genders.length,
                    itemBuilder: (context, index) {
                      final key = _genders.keys.elementAt(index);
                      final localeKey = _genders[key]!;
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 70,
                            child: Row(
                              spacing: 8.h,
                              children: [
                                Radio<String>(
                                  value: key,
                                  groupValue: selectedGender,
                                  activeColor: AppColors.errorColor,
                                  onChanged: (String? value) {
                                    if (value == null) return;
                                    setState(() {
                                      selectedGender = value;
                                    });
                                    _onInputChanged();
                                    Navigator.of(context).pop();
                                  },
                                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                ),
                                localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                              ],
                            ).onPress(() {
                              setState(() {
                                selectedGender = key;
                              });
                              _onInputChanged();
                              Navigator.pop(context);
                            }),
                          ),
                        ],
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider(height: 1, color: Color(0xFFEEEEEE));
                    },
                  ),
                ),
                onOkPressed: () {},
              );
            }),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === AGE ROW (unchanged) ===
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.age, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      "Age (11-120) yrs".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _ageController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '20',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black87, height: 1.0),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === HEIGHT ROW ===
            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: [
                      "Height".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(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          (_heightUnits[selectedHeightUnit] ?? selectedHeightUnit).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    _showUnitBottomSheet(context, dialogService, _heightUnits, selectedHeightUnit, (value) {
                      setState(() { selectedHeightUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === WEIGHT ROW ===
            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: [
                      "Weight".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(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          (_weightUnits[selectedWeightUnit] ?? selectedWeightUnit).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    _showUnitBottomSheet(context, dialogService, _weightUnits, selectedWeightUnit, (value) {
                      setState(() { selectedWeightUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === ACTIVITY LEVEL ROW ===
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.activity, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          LocaleKeys.activityLevel.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          (_activityLevels[selectedActivityLevel] ?? selectedActivityLevel).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                    ],
                  ),
                ),
                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down),
                SizedBox(width: 4.w),
              ],
            ).paddingSymmetrical(0.w, 16.w).onPress(() {
              dialogService.showFamilyBottomSheetWithoutHWithChild(
                label: LocaleKeys.selectActivityLevel.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: _activityLevels.length,
                    itemBuilder: (context, index) {
                      final key = _activityLevels.keys.elementAt(index);
                      final localeKey = _activityLevels[key]!;
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 70,
                            child: Row(
                              spacing: 8.h,
                              children: [
                                Radio<String>(
                                  value: key,
                                  groupValue: selectedActivityLevel,
                                  activeColor: AppColors.errorColor,
                                  onChanged: (String? value) {
                                    if (value == null) return;
                                    setState(() {
                                      selectedActivityLevel = value;
                                    });
                                    _onInputChanged();
                                    Navigator.pop(context);
                                  },
                                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                ),
                                localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                              ],
                            ).onPress(() {
                              setState(() {
                                selectedActivityLevel = key;
                              });
                              _onInputChanged();
                              Navigator.pop(context);
                            }),
                          ),
                        ],
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider(height: 1, color: Color(0xFFEEEEEE));
                    },
                  ),
                ),
                onOkPressed: () {},
              );
            }),
            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: LocaleKeys.calculateCaloriesBasedOnFactors.tr()
                      .toText12(isBold: true, color: AppColors.inputLabelTextColor),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
          ],
        ),
      );
    });
  }

  void _showUnitBottomSheet(BuildContext context, DialogService dialogService, Map<String, String> units, String currentValue, Function(String) onSelected) {
    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: units.length,
          itemBuilder: (context, index) {
            final key = units.keys.elementAt(index);
            final localeKey = units[key]!;
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(
                  height: 70,
                  child: Row(
                    spacing: 8.h,
                    children: [
                      Radio<String>(
                        value: key,
                        groupValue: currentValue,
                        activeColor: AppColors.errorColor,
                        onChanged: (String? value) {
                          if (value == null) return;
                          onSelected(value);
                          Navigator.pop(context);
                        },
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                    ],
                  ).onPress(() {
                    onSelected(key);
                    Navigator.pop(context);
                  }),
                ),
              ],
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(height: 1, color: Color(0xFFEEEEEE));
          },
        ),
      ),
      onOkPressed: () {},
    );
  }
}
