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/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 IdealBodyWeightWidget extends StatefulWidget {
  Function(dynamic result)? onChange;

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

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

class _IdealBodyWeightWidgetState extends State<IdealBodyWeightWidget> {
  final TextEditingController _heightController = TextEditingController();
  final TextEditingController _weightController = 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> _bodyFrameSizes = {
    'Small (fingers overlaps)': LocaleKeys.bodyFrameSmall,
    'Medium (fingers touch)': LocaleKeys.bodyFrameMedium,
    "Large (fingers don't touch)": LocaleKeys.bodyFrameLarge,
  };
  String selectedHeightUnit = 'cm';
  String selectedWeightUnit = 'kg';
  String selectedBodyFrameSize = 'Medium (fingers touch)';

  @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.calculateIBW(
      heightText: _heightController.text,
      weightText: _weightController.text,
      heightUnit: selectedHeightUnit,
      weightUnit: selectedWeightUnit,
      bodyFrameSize: selectedBodyFrameSize,
    );
    if (widget.onChange != null) widget.onChange!(provider.ibwResultMap);
  }

  @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: [
                      "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(() {
                    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: selectedHeightUnit,
                                        activeColor: AppColors.errorColor,
                                        onChanged: (String? value) {
                                          if (value == null) return;
                                          setState(() {
                                            selectedHeightUnit = value;
                                          });
                                          _onInputChanged();
                                          Navigator.pop(context);
                                        },
                                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                      ),
                                      localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                                    ],
                                  ).onPress(() {
                                    setState(() {
                                      selectedHeightUnit = key;
                                    });
                                    _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.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(() {
                    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: _weightUnits.length,
                          itemBuilder: (context, index) {
                            final key = _weightUnits.keys.elementAt(index);
                            final localeKey = _weightUnits[key]!;
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SizedBox(
                                  height: 70,
                                  child: Row(
                                    spacing: 8.h,
                                    children: [
                                      Radio<String>(
                                        value: key,
                                        groupValue: selectedWeightUnit,
                                        activeColor: AppColors.errorColor,
                                        onChanged: (String? value) {
                                          if (value == null) return;
                                          setState(() {
                                            selectedWeightUnit = value;
                                          });
                                          _onInputChanged();
                                          Navigator.pop(context);
                                        },
                                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                      ),
                                      localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                                    ],
                                  ).onPress(() {
                                    setState(() {
                                      selectedWeightUnit = key;
                                    });
                                    _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.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.bodyFrameSize.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                          (_bodyFrameSizes[selectedBodyFrameSize] ?? selectedBodyFrameSize).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.selectBodyFrameSize.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: _bodyFrameSizes.length,
                    itemBuilder: (context, index) {
                      final key = _bodyFrameSizes.keys.elementAt(index);
                      final localeKey = _bodyFrameSizes[key]!;
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 70,
                            child: Row(
                              spacing: 8.h,
                              children: [
                                Radio<String>(
                                  value: key,
                                  groupValue: selectedBodyFrameSize,
                                  activeColor: AppColors.errorColor,
                                  onChanged: (String? value) {
                                    if (value == null) return;
                                    setState(() {
                                      selectedBodyFrameSize = value;
                                    });
                                    _onInputChanged();
                                    Navigator.pop(context);
                                  },
                                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                ),
                                localeKey.tr().toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
                              ],
                            ).onPress(() {
                              setState(() {
                                selectedBodyFrameSize = 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.ibwAlert.tr().toText12(isBold: true, color: AppColors.inputLabelTextColor),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
          ],
        ),
      );
    });
  }
}
