import 'dart:math';

import 'package:hmg_patient_app/main.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/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 'result_page.dart';

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

class BMICalculator extends StatefulWidget {
  @override
  _BMICalculatorState createState() => _BMICalculatorState();
}

class _BMICalculatorState extends State<BMICalculator> {
  TextEditingController textController = TextEditingController();
  String? textResult;
  String? msg;
  double? bmiResult;

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

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

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

  double convertToCm(double number) {
    return number * 30.48;
  }

  double convertToKg(double number) {
    return number / 2.205;
  }

  double calculateBMI() {
    if (!_isHeightCM) _heightValue = convertToCm(_heightValue.toDouble());

    if (!_isWeightKG) _weightValue = convertToKg(_weightValue);

    bmiResult = _weightValue / pow(_heightValue / 100, 2);

    return bmiResult!;
  }

  void showTextResult(BuildContext context) {
    if (bmiResult! >= 30) {
      textResult = TranslationBase.of(context).obese;
    } else if (bmiResult! < 30 && bmiResult! >= 25) {
      textResult = TranslationBase.of(context).overWeight;
    } else if (bmiResult! < 25 && bmiResult! >= 18.5) {
      textResult = TranslationBase.of(context).healthy;
    } else if (bmiResult! < 18.5) {
      textResult = TranslationBase.of(context).underWeight;
    }
  }

  void showMsg(BuildContext context) {
    if (bmiResult! >= 30) {
      msg = TranslationBase.of(context).bmiCalcMsgObese;
    } else if (bmiResult! < 30 && bmiResult! >= 25) {
      msg = TranslationBase.of(context).bmiCalcMsgOverweight;
    } else if (bmiResult! < 25 && bmiResult! >= 18.5) {
      msg = TranslationBase.of(context).bmiCalcMsgHealthy;
    } else if (bmiResult! < 18.5) {
      msg = TranslationBase.of(context).bmiCalcMsgUnderWeight;
    }
  }

  @override
  void initState() {
    super.initState();
    textController.text = '0'; // Setting the initial value for the field.
    _heightValue = 100;
    _weightValue = 50;
    _heightController.text = _heightValue.toStringAsFixed(0);
    _weightController.text = _weightValue.toStringAsFixed(0);

    _isWeightKG = true;
    _isHeightCM = true;
  }

  Widget build(BuildContext 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,
      showHomeAppBarIcon: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      appBarTitle: "${TranslationBase.of(context).bmi} ${TranslationBase.of(context).calcHealth}",
      body: Column(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    TranslationBase.of(context).bmiCalcDesc,
                    style: TextStyle(
                      fontSize: 14.0,
                      letterSpacing: -0.56,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  mHeight(24),
                  _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,
                  ),
                  mHeight(12),
                  _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,
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.all(16),
            child: SecondaryButton(
              label: TranslationBase.of(context).calculate,
              color: CustomColors.accentColor,
              onTap: () {
                setState(() {
                  calculateBMI();
                  showTextResult(context);
                  showMsg(context);
                  {
                    Navigator.push(
                      context,
                      FadePage(
                        page: ResultPage(
                          finalResult: bmiResult!,
                          textResult: textResult!,
                          msg: msg!,
                        ),
                      ),
                    );
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  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 StatefulWidget {
  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
  State<CommonDropDownView> createState() => _CommonDropDownViewState();
}

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

extension BorderedContainer on Widget {
  Widget get withBorderedContainer => 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: this,
      );
}
