import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'ideal_body_result_page.dart';

const activeCardColor = Color(0xff70777A);
const inactiveCardColor = Color(0xffFAFAFd);

class IdealBody extends StatefulWidget {
  @override
  _IdealBodyState createState() => _IdealBodyState();
}

class _IdealBodyState extends State<IdealBody> {
  bool isMale = false;
  bool isHeightCm = true;

  Color kgCard = activeCardColor;
  Color lbCard = inactiveCardColor;
  Color cmCard = activeCardColor;
  Color ftCard = inactiveCardColor;

  // int age = 0;
  // int height = 0;
  double heightInches;
  double minRange;
  double maxRange;
  double overWeightBy;
  int weight = 0;
  double idealWeight = 0;
  String dropdownValue = null;
  double calories = 0;
  String textResult = '';
  double maxIdealWeight;
  double heightFeet;

  final GlobalKey clinicDropdownKey = GlobalKey();
  bool _isHeightCM = true;
  bool _isWeightKG = true;
  double _heightValue = 0;
  double _weightValue = 0;

  TextEditingController _heightController = new TextEditingController();
  TextEditingController _weightController = TextEditingController();

  List<PopupMenuItem> _heightPopupList = List();
  List<PopupMenuItem> _weightPopupList = List();

  void calculateIdealWeight() {
    var height = int.parse(_heightController.text);
    var weight = double.parse(_weightController.text);
    var inchesVal = ((height) * .39370078740157477);
    var meters = height / 100;
    var feetVal = (inchesVal / 12).floor().round();
    inchesVal = (inchesVal % 12).roundToDouble();
    var kgValue = (weight * 2.2).floor();
    var heightFeet = feetVal;
    var heightInches = inchesVal;
    weight = kgValue.floorToDouble();
    var idealWeight = (((((heightFeet * 12) + heightInches) - 60) * 6) + 106);
    if (dropdownValue == TranslationBase.of(context).smallFinger) {
      idealWeight = idealWeight - 10;
    } else if (dropdownValue == TranslationBase.of(context).mediumFinger) {
      idealWeight = idealWeight;
    } else if (dropdownValue == TranslationBase.of(context).largeFinger) {
      idealWeight = idealWeight + 10;
    }
    var maxIdealWeight = (((idealWeight).floorToDouble() * 1.1) * 100).round() / 100;
    var overWeightBy = ((weight - double.parse(maxIdealWeight.toString())) * 100).round() / 100;
    var difference = (((overWeightBy / 2.2) * 100) / 100).round(); //+ Loc.healthCalPage.IBWKg;  Loc.healthCalPage.IBWRange
    var minRange = ((idealWeight / 2.2) * 10).round() / 10;
    var maxRange = ((maxIdealWeight / 2.2) * 100).round() / 100; //+ //Loc.healthCalPage.IBWKg;
    idealWeight = weight / idealWeight;
    idealWeight = (idealWeight * 100).round() / 100;
    this.overWeightBy = overWeightBy;
    this.minRange = minRange;
    this.maxRange = maxIdealWeight;
    this.idealWeight = idealWeight;
  }

  @override
  Widget build(BuildContext context) {
    if (dropdownValue == null) dropdownValue = TranslationBase.of(context).mediumFinger;
    _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).idealBody,
      showHomeAppBarIcon: false,
      appBarIcons: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
          child: Icon(
            Icons.info_outline,
            color: Colors.white,
          ),
        )
      ],
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.all(21),
                child: Column(
                  children: [
                    Text(
                      TranslationBase.of(context).idealBodyWeight,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.56,
                        color: CustomColors.textColor,
                      ),
                    ),
                    SizedBox(
                      height: 5.0,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        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).bodyFrameSize,
                                        style: TextStyle(
                                          fontSize: 11,
                                          letterSpacing: -0.44,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      Container(
                                        height: 18,
                                        child: DropdownButtonHideUnderline(
                                          child: DropdownButton<String>(
                                            value: dropdownValue,
                                            icon: Icon(Icons.arrow_downward),
                                            key: clinicDropdownKey,
                                            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).smallFinger,
                                              TranslationBase.of(context).mediumFinger,
                                              TranslationBase.of(context).largeFinger,
                                            ].map<DropdownMenuItem<String>>((String value) {
                                              return DropdownMenuItem<String>(
                                                value: value,
                                                child: Text(value),
                                              );
                                            }).toList(),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Icon(Icons.keyboard_arrow_down),
                              ],
                            ),
                          ).withBorderedContainer,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          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(() {
                  calculateIdealWeight();
                  {
                    Navigator.push(
                      context,
                      FadePage(
                          page: IdealBodyResult(
                        idealBodyWeight: idealWeight,
                        minRange: minRange,
                        mixRange: maxRange,
                        overWeightBy: overWeightBy,
                        textResult: textResult,
                      )),
                    );
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  void openDropdown(GlobalKey key) {
    GestureDetector detector;
    void searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget;
          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, null),
              onSelected: (value) {
                onUnitTap(value);
              },
              itemBuilder: (context) => _list),
        )
      ],
    ).withBorderedContainer;
  }
}

// todo 'sikander' move these to separate file once usability known
class CommonDropDownView extends StatelessWidget {
  final String title;
  final String value;
  final VoidCallback 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(
      onTap: callback,
      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),
          )
        ],
      ),
    );
  }
}
