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:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.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';

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

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

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

class _BodyFatWidgetState extends State<BodyFatWidget> {
  final TextEditingController _heightController = TextEditingController();
  final TextEditingController _neckController = TextEditingController();
  final TextEditingController _waistController = TextEditingController();
  final TextEditingController _hipController = TextEditingController();

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

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

  String selectedHeightUnit = 'cm';
  String selectedNeckUnit = 'in';
  String selectedWaistUnit = 'in';
  String selectedHipUnit = 'in';
  String selectedGender = "Male";

  @override
  void initState() {
    super.initState();
    _heightController.addListener(_onInputChanged);
    _neckController.addListener(_onInputChanged);
    _waistController.addListener(_onInputChanged);
    _hipController.addListener(_onInputChanged);
  }

  @override
  void dispose() {
    _heightController.removeListener(_onInputChanged);
    _neckController.removeListener(_onInputChanged);
    _waistController.removeListener(_onInputChanged);
    _hipController.removeListener(_onInputChanged);
    _heightController.dispose();
    _neckController.dispose();
    _waistController.dispose();
    _hipController.dispose();
    super.dispose();
  }

  void _onInputChanged() {
    final provider = Provider.of<HealthCalcualtorViewModel>(context, listen: false);
    provider.calculateBodyFat(
      heightText: _heightController.text,
      neckText: _neckController.text,
      waistText: _waistController.text,
      hipText: _hipController.text,
      heightUnit: selectedHeightUnit,
      neckUnit: selectedNeckUnit,
      waistUnit: selectedWaistUnit,
      hipUnit: selectedHipUnit,
      gender: selectedGender,
    );
    if (widget.onChange != null) widget.onChange!(provider.bodyFatResultMap);
  }

  @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.pop(context);
                                  },
                                  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)),
            // === 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, selectedHeightUnit, (value) {
                      setState(() { selectedHeightUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === NECK 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: [
                      "Neck".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _neckController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '7',
                            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[selectedNeckUnit] ?? selectedNeckUnit).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    _showUnitBottomSheet(context, dialogService, selectedNeckUnit, (value) {
                      setState(() { selectedNeckUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === WAIST 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: [
                      "Waist".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _waistController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '30',
                            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[selectedWaistUnit] ?? selectedWaistUnit).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    _showUnitBottomSheet(context, dialogService, selectedWaistUnit, (value) {
                      setState(() { selectedWaistUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            // === HIP 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: [
                      "Hip".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _hipController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '0',
                            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[selectedHipUnit] ?? selectedHipUnit).tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                      SizedBox(width: 12.w),
                      Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                    ],
                  ).onPress(() {
                    _showUnitBottomSheet(context, dialogService, selectedHipUnit, (value) {
                      setState(() { selectedHipUnit = value; });
                      _onInputChanged();
                    });
                  }),
                ),
              ],
            ).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: LocaleKeys.bodyFatAlert.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
          ],
        ),
      );
    });
  }

  void _showUnitBottomSheet(BuildContext context, DialogService dialogService, 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: _heightUnits.length,
          itemBuilder: (context, index) {
            final key = _heightUnits.keys.elementAt(index);
            final localeKey = _heightUnits[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: () {},
    );
  }
}
