import 'dart:math';

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/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 'body_fat_result_page.dart';

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

class BodyFat extends StatefulWidget {
  @override
  _BodyFatState createState() => _BodyFatState();
}

class _BodyFatState extends State<BodyFat> {
  final GlobalKey clinicDropdownKey = GlobalKey();
  bool _isHeightCM = true;
  bool _isNeckKG = true;
  bool _isWaistKG = true;
  bool _isHipKG = true;
  double _heightValue = 0;
  double _neckValue = 0;
  double _waistValue = 0;
  double _hipValue = 0;

  TextEditingController _heightController = TextEditingController();
  TextEditingController _neckController = TextEditingController();
  TextEditingController _waistController = TextEditingController();
  TextEditingController _hipController = TextEditingController();

  List<PopupMenuItem> _heightPopupList = [];
  List<PopupMenuItem> _neckPopupList = [];
  List<PopupMenuItem> _waistPopupList = [];
  List<PopupMenuItem> _hipPopupList = [];

  bool isMale = false;

  // bool isHeightCm = true;
  Color maleCard = activeCardColorGender;
  Color femaleCard = inactiveCardColorGender;

  // Color neckCmCard = activeCardColor;
  // Color neckFtCard = inactiveCardColor;
  Color waistCmCard = activeCardColor;
  Color waistFtCard = inactiveCardColor;
  Color hipCmCard = activeCardColor;
  Color hipFtCard = inactiveCardColor;
  Color cmCard = activeCardColor;
  Color ftCard = inactiveCardColor;

  // int neck = 10;
  // int heightCm = 0;
  // int heightFt = 0;
  // int hip = 5;
  double? heightInches;
  double? minRange;
  double? maxRange;
  double? overWeightBy;

  // int waist = 5;
  double bodyFat = 0;
  double fat = 0;
  String? dropdownValue;
  double calories = 0;
  String textResult = '';

  @override
  void initState() {
    _neckController.text = _neckValue.toString();
    _hipController.text = _hipValue.toString();
    _waistController.text = _waistValue.toString();
    _heightController.text = _heightValue.toString();
    super.initState();
  }

  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 updateColorWaist(int type) {
    //MG/DLT card
    if (type == 1) {
      if (waistCmCard == inactiveCardColor) {
        waistCmCard = activeCardColor;
        waistFtCard = inactiveCardColor;
      } else {
        waistCmCard = inactiveCardColor;
      }
    }
    if (type == 2) {
      if (waistFtCard == inactiveCardColor) {
        waistFtCard = activeCardColor;
        waistCmCard = inactiveCardColor;
      } else {
        waistFtCard = inactiveCardColor;
      }
    }
  }

  void updateColorHip(int type) {
    //MG/DLT card
    if (type == 1) {
      if (hipCmCard == inactiveCardColor) {
        hipCmCard = activeCardColor;
        hipFtCard = inactiveCardColor;
      } else {
        hipCmCard = inactiveCardColor;
      }
    }
    if (type == 2) {
      if (hipFtCard == inactiveCardColor) {
        hipFtCard = activeCardColor;
        hipCmCard = inactiveCardColor;
      } else {
        hipFtCard = inactiveCardColor;
      }
    }
  }

  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 calculateBodyFat() {
    if (isMale == true) {
      bodyFat = 495 / (1.0324 - 0.19077 * (log(_waistValue - _neckValue) / ln10) + 0.15456 * (log(int.parse(_heightController.text)) / ln10)) - 450;
      fat = (bodyFat * 10) / 10.round();
    } else if (isMale == false) {
      bodyFat = 495 / (1.29579 - 0.35004 * (log(_waistValue + _hipValue - _neckValue) / ln10) + 0.22100 * (log(int.parse(_heightController.text)) / ln10)) - 450;
      fat = (bodyFat * 10) / 10.round();
    }
    if (fat <= 0) {
      fat = 0;
    }
  }

  void showTextResult(BuildContext context) {
    if (isMale == false) {
      if (bodyFat > 9 && bodyFat <= 13) {
        textResult = TranslationBase.of(context).essential;
      } else if (bodyFat > 13 && bodyFat <= 20) {
        textResult = TranslationBase.of(context).athlete;
      } else if (bodyFat > 20 && bodyFat <= 24) {
        textResult = TranslationBase.of(context).fitness;
      } else if (bodyFat > 24 && bodyFat <= 31) {
        textResult = TranslationBase.of(context).acceptable;
      } else if (bodyFat > 31 && bodyFat <= 60) {
        textResult = TranslationBase.of(context).underObese;
      } else if (bodyFat > 60) {
        textResult = TranslationBase.of(context).crossedLimits;
      } else if (bodyFat <= 9) {
        textResult = TranslationBase.of(context).lowLimits;
      }
    } else {
      if (bodyFat > 5 && fat <= 13) {
        textResult = TranslationBase.of(context).essential;
      } else if (bodyFat > 13 && bodyFat <= 17) {
        textResult = TranslationBase.of(context).athlete;
      } else if (bodyFat > 17 && bodyFat <= 24) {
        textResult = TranslationBase.of(context).fitness;
      } else if (bodyFat > 24 && bodyFat <= 45) {
        textResult = TranslationBase.of(context).underObese;
      } else if (bodyFat > 45) {
        textResult = TranslationBase.of(context).crossedLimits;
      } else if (bodyFat <= 5) {
        textResult = TranslationBase.of(context).lowLimits;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    _neckPopupList = <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)
    ];

    _waistPopupList = <PopupMenuItem>[
      PopupMenuItem(
        child: Text(TranslationBase.of(context).kg),
        value: true,
      ),
      PopupMenuItem(
          child: Text(
            TranslationBase.of(context).lb,
          ),
          value: false)
    ];
    _hipPopupList = <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).bodyFatTitle,
      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(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      TranslationBase.of(context).bodyFatDesc,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.56,
                        color: CustomColors.textColor,
                      ),
                    ),
                    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,
                    ),
                    _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).neck,
                      _neckController,
                      1,
                      270,
                      _neckValue,
                      (text) {
                        _neckController.text = text;
                      },
                      (value) {
                        _neckValue = value;
                      },
                      _isNeckKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
                      (value) {
                        if (_isNeckKG != value) {
                          setState(() {
                            _isNeckKG = value;
                          });
                        }
                      },
                      _neckPopupList,
                    ),
                    SizedBox(
                      height: 12.0,
                    ),
                    _commonInputAndUnitRow(
                      TranslationBase.of(context).waist,
                      _waistController,
                      1,
                      270,
                      _waistValue,
                      (text) {
                        _waistController.text = text;
                      },
                      (value) {
                        _waistValue = value;
                      },
                      _isWaistKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
                      (value) {
                        if (_isWaistKG != value) {
                          setState(() {
                            _isWaistKG = value;
                          });
                        }
                      },
                      _waistPopupList,
                    ),
                    SizedBox(
                      height: 12.0,
                    ),
                    _commonInputAndUnitRow(
                      TranslationBase.of(context).hip,
                      _hipController,
                      1,
                      270,
                      _hipValue,
                      (text) {
                        _hipController.text = text;
                      },
                      (value) {
                        _hipValue = value;
                      },
                      _isHipKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
                      (value) {
                        if (_isHipKG != value) {
                          setState(() {
                            _isHipKG = value;
                          });
                        }
                      },
                      _hipPopupList,
                    ),
                    SizedBox(
                      height: 12.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(() {
                  calculateBodyFat();
                  showTextResult(context);

                  {
                    Navigator.push(
                      context,
                      FadePage(
                          page: FatResult(
                        bodyFat: bodyFat,
                        fat: fat,
                        textResult: textResult,
                      )),
                    );
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  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,
            enabled: true,
          ),
        )
      ],
    ).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 GestureDetector(
      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),
          )
        ],
      ),
    );
  }
}
