import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/secondary_button.dart';
import 'package:hmg_patient_app/widgets/data_display/text.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'bmr_result_page.dart';

const activeCardColorGender = Color(0xffC5272D);
const inactiveCardColorGender = Color(0xffFAFAFd);
const activeCardColor = Color(0xff70777A);
const inactiveCardColor = Color(0xffFAFAFd);

class BmrCalculator extends StatefulWidget {
  @override
  _BmrCalculatorState createState() => _BmrCalculatorState();
}

class _BmrCalculatorState extends State<BmrCalculator> {
  bool isMale = false;
  bool isHeightCm = true;
  Color maleCard = activeCardColorGender;
  Color femaleCard = inactiveCardColorGender;
  Color kgCard = activeCardColor;
  Color lbCard = inactiveCardColor;
  Color cmCard = activeCardColor;
  Color ftCard = inactiveCardColor;

  final GlobalKey clinicDropdownKey = GlobalKey();
  TextEditingController ageController = new TextEditingController();
  TextEditingController _heightController = new TextEditingController();
  TextEditingController _weightController = TextEditingController();

  bool _isHeightCM = true;
  bool _isWeightKG = true;
  double _heightValue = 150;
  double _weightValue = 40;

  List<PopupMenuItem> _heightPopupList = [];
  List<PopupMenuItem> _weightPopupList = [];

  // int age = 0;
  // int height = 0;
  // int weight = 0;
  double bmrResult = 0;
  String dropdownValue = '';
  double calories = 0;

  void updateColor(int type) {
    //MG/DLT card
    if (type == 1) {
      if (maleCard == inactiveCardColorGender) {
        maleCard = activeCardColorGender;
        femaleCard = inactiveCardColorGender;
      } else {
        maleCard = inactiveCardColorGender;
      }
    }
    if (type == 2) {
      if (femaleCard == inactiveCardColorGender) {
        femaleCard = activeCardColorGender;
        maleCard = inactiveCardColorGender;
      } else {
        femaleCard = inactiveCardColorGender;
      }
    }
  }

  void updateColorHeight(int type) {
    //MG/DLT card
    if (type == 1) {
      if (cmCard == inactiveCardColor) {
        cmCard = activeCardColor;
        ftCard = inactiveCardColor;
      } else {
        cmCard = inactiveCardColor;
      }
    }
    if (type == 2) {
      if (ftCard == inactiveCardColor) {
        ftCard = activeCardColor;
        cmCard = inactiveCardColor;
      } else {
        ftCard = inactiveCardColor;
      }
    }
  }

  void updateColorWeight(int type) {
    //MG/DLT card
    if (type == 1) {
      if (kgCard == inactiveCardColor) {
        kgCard = activeCardColor;
        lbCard = inactiveCardColor;
      } else {
        kgCard = inactiveCardColor;
      }
    }
    if (type == 2) {
      if (lbCard == inactiveCardColor) {
        lbCard = activeCardColor;
        kgCard = inactiveCardColor;
      } else {
        lbCard = inactiveCardColor;
      }
    }
  }

  void calculateBmr() {
    if (isMale == true) {
      bmrResult = 66.5 + (13.75 * int.parse(_weightController.text)) + (5.003 * int.parse(_heightController.text)) - (6.755 * int.parse(ageController.text));
    } else if (isMale == false) {
      bmrResult = 655.0955 + (9.5634 * int.parse(_weightController.text)) + (1.850 * int.parse(_heightController.text)) - (4.676 * int.parse(ageController.text));
    }

    bmrResult = bmrResult.roundToDouble();
  }

  void calculateCalories(BuildContext context) {
    if (dropdownValue == TranslationBase.of(context).almostInactive) {
      calories = bmrResult * 1.2;
    } else if (dropdownValue == TranslationBase.of(context).lightActive1) {
      calories = bmrResult * 1.375;
    } else if (dropdownValue == TranslationBase.of(context).veryActive) {
      calories = bmrResult * 1.55;
    } else if (dropdownValue == TranslationBase.of(context).superActive) {
      calories = bmrResult * 1.725;
    } else if (dropdownValue == "") {
      calories = bmrResult * 10.725;
    }
  }

  @override
  Widget build(BuildContext context) {
    dropdownValue = TranslationBase.of(context).lightActive1;
    ProjectViewModel projectViewModel = Provider.of(context);
    _weightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)];
    _heightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)];

    return AppScaffold(
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      appBarTitle: TranslationBase.of(context).bmr,
      showHomeAppBarIcon: false,
      appBarIcons: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
          child: Icon(
            Icons.info_outline,
            color: Colors.white,
          ),
        )
      ],
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(21.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        TranslationBase.of(context).calculateAmount,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.56,
                          color: CustomColors.textColor,
                        ),
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 20,
                          ),
                          Text(
                            TranslationBase.of(context).selectGender,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.56,
                              color: CustomColors.textColor,
                            ),
                          ),
                          SizedBox(
                            height: 8.0,
                          ),
                          Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        updateColor(1);
                                        isMale = false;
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        Container(
                                          decoration: containerColorRadiusBorderWidth(Colors.white, 1000, CustomColors.darkGreyColor, 1),
                                          width: 24,
                                          height: 24,
                                          padding: EdgeInsets.all(4),
                                          child: Container(
                                            width: double.infinity,
                                            height: double.infinity,
                                            decoration: containerRadius(!isMale ? CustomColors.accentColor : Colors.white, 100),
                                          ),
                                        ),
                                        mWidth(12),
                                        Text(
                                          TranslationBase.of(context).female,
                                          style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w600,
                                            letterSpacing: -0.56,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        updateColor(2);
                                        isMale = true;
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        Container(
                                          decoration: containerColorRadiusBorderWidth(Colors.white, 1000, CustomColors.darkGreyColor, 1),
                                          width: 24,
                                          height: 24,
                                          padding: EdgeInsets.all(4),
                                          child: Container(
                                            width: double.infinity,
                                            height: double.infinity,
                                            decoration: containerRadius(isMale ? CustomColors.accentColor : Colors.white, 100),
                                          ),
                                        ),
                                        mWidth(12),
                                        Text(
                                          TranslationBase.of(context).male,
                                          style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w600,
                                            letterSpacing: -0.56,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 12.0,
                          ),
                          inputWidget(TranslationBase.of(context).age11_120Years, "0", ageController),
                          SizedBox(
                            height: 12.0,
                          ),
                          _commonInputAndUnitRow(
                            TranslationBase.of(context).height,
                            _heightController,
                            1,
                            270,
                            _heightValue,
                            (text) {
                              _heightController.text = text;
                            },
                            (value) {
                              _heightValue = value;
                            },
                            _isHeightCM ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
                            (value) {
                              if (_isHeightCM != value) {
                                setState(() {
                                  _isHeightCM = value;
                                });
                              }
                            },
                            _heightPopupList,
                          ),
                          SizedBox(
                            height: 12.0,
                          ),
                          _commonInputAndUnitRow(
                            TranslationBase.of(context).weight,
                            _weightController,
                            1,
                            270,
                            _weightValue,
                            (text) {
                              _weightController.text = text;
                            },
                            (value) {
                              _weightValue = value;
                            },
                            _isWeightKG ? TranslationBase.of(context).kg : TranslationBase.of(context).pound,
                            (value) {
                              if (_isWeightKG != value) {
                                setState(() {
                                  _isWeightKG = value;
                                });
                              }
                            },
                            _weightPopupList,
                          ),
                          SizedBox(
                            height: 12.0,
                          ),
                          InkWell(
                            onTap: () {
                              // dropdownKey.currentState;
                              openDropdown(clinicDropdownKey);
                            },
                            child: Container(
                              // width: double.infinity,
                              // decoration: containerRadius(Colors.white, 12),
                              // padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
                              child: Row(
                                children: [
                                  Flexible(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          TranslationBase.of(context).activityLevel,
                                          style: TextStyle(
                                            fontSize: 11,
                                            letterSpacing: -0.44,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                        Container(
                                          height: 18,
                                          child: DropdownButtonHideUnderline(
                                            child: DropdownButton<String>(
                                              value: dropdownValue,
                                              key: clinicDropdownKey,
                                              icon: Icon(Icons.arrow_downward),
                                              iconSize: 0,
                                              elevation: 16,
                                              isExpanded: true,
                                              style: TextStyle(color: Colors.black87),
                                              underline: Container(
                                                height: 2,
                                                color: Colors.black54,
                                              ),
                                              onChanged: (String? newValue) {
                                                setState(() {
                                                  dropdownValue = newValue!;
                                                });
                                              },
                                              items: <String>[
                                                TranslationBase.of(context).almostInactive,
                                                TranslationBase.of(context).lightActive1,
                                                TranslationBase.of(context).veryActive,
                                                TranslationBase.of(context).superActive
                                              ].map<DropdownMenuItem<String>>((String value) {
                                                return DropdownMenuItem<String>(
                                                  value: value,
                                                  child: Text(value),
                                                );
                                              }).toList(),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Icon(Icons.keyboard_arrow_down),
                                ],
                              ),
                            ).withBorderedContainer,
                          ),
                          SizedBox(
                            height: 25.0,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0),
              color: Colors.white,
              child: SecondaryButton(
                label: TranslationBase.of(context).calculate,
                color: CustomColors.accentColor,
                onTap: () {
                  setState(() {
                    calculateBmr();
                    calculateCalories(context);

                    {
                      Navigator.push(
                        context,
                        FadePage(
                            page: BmrResultPage(
                          bmrResult: bmrResult,
                          calories: calories,
                        )),
                      );
                    }
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void openDropdown(GlobalKey key) {
    GestureDetector? detector;

    void searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget as GestureDetector?;
          //return false;
        } else {
          searchForGestureDetector(element);
        }

        //return true;
      });
    }

    searchForGestureDetector(key.currentContext!);
    assert(detector != null);

    detector!.onTap!();
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.number,
                    controller: _controller,
                    onChanged: (value) => {},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

  Widget _commonInputAndUnitRow(_title, _controller, double _minValue, double _maxValue, double _valueOrg, Function(String) onTextValueChange, Function(double) onValueChange, String unitTitle,
      Function(bool) onUnitTap, _list) {
    return Row(
      children: [
        Expanded(
          flex: 3,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                _title,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xff2E303A),
                  letterSpacing: -0.44,
                ),
              ),
              TextField(
                controller: _controller,
                keyboardType: TextInputType.number,
                onChanged: (value) {
                  double _value = double.parse(value);
                  if (_value > _maxValue) {
                    onTextValueChange(_maxValue.toStringAsFixed(0));
                    onValueChange(_maxValue);
                    return;
                  } else if (_value < _minValue) {
                    onTextValueChange(_minValue.toStringAsFixed(0));
                    onValueChange(_minValue);
                    return;
                  } else if (_value >= _minValue && _value <= _maxValue) {
                    onValueChange(_value);
                    return;
                  }
                },
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                ],
                style: TextStyle(
                  color: Color(0xff575757),
                  letterSpacing: -0.56,
                ),
                decoration: InputDecoration(
                  isDense: true,
                  hintText: "0",
                  hintStyle: TextStyle(
                    fontSize: 14,
                    height: 21 / 14,
                    fontWeight: FontWeight.w400,
                    color: Color(0xff575757),
                    letterSpacing: -0.56,
                  ),
                  contentPadding: EdgeInsets.zero,
                  border: InputBorder.none,
                  focusedBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                ),
              ),
            ],
          ),
        ),
        Container(height: 34, width: 1, color: Color(0xffE0E0E0), margin: EdgeInsets.only(left: 12, right: 12)),
        Expanded(
          flex: 1,
          child: PopupMenuButton(
              child: CommonDropDownView(
                TranslationBase.of(context).unit,
                unitTitle,
                (val) async {
                  final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
                  await showMenu(
                    context: context,
                    position: RelativeRect.fromRect(val.globalPosition & const Size(40, 40), Offset.zero & overlay.size),
                    items: _list,
                    elevation: 8.0,
                  ).then((val) {
                    print(val);
                    onUnitTap(val);
                  });
                },
              ),
              itemBuilder: (context) => _list),
        )
      ],
    ).withBorderedContainer;
  }
}

// todo 'sikander' move these to separate file once usability known
class CommonDropDownView extends StatelessWidget {
  final String title;
  final String value;
  void Function(TapDownDetails details) callback;
  final IconData? iconData;

  CommonDropDownView(this.title, this.value, this.callback, {Key? key, this.iconData}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTapDown: (val) => callback(val),
      child: Row(
        children: [
          Expanded(
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xff2E303A),
                  letterSpacing: -0.44,
                ),
              ),
              Text(
                value,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                  color: Color(0xff575757),
                  letterSpacing: -0.56,
                ),
              ),
            ]),
          ),
          Icon(
            iconData ?? Icons.keyboard_arrow_down_sharp,
            color: Color(0xff2E303A),
          )
        ],
      ),
    );
  }
}
