import 'package:aitrainer_app/bloc/exercise_new/exercise_new_bloc.dart';
import 'package:aitrainer_app/util/app_localization.dart';
import 'package:aitrainer_app/model/fitness_state.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/library/dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'app_bar.dart';
import 'package:keyboard_actions/keyboard_actions.dart';

// ignore: must_be_immutable
class BMR extends StatefulWidget {
  final ExerciseNewBloc exerciseBloc;

  BMR({required this.exerciseBloc});

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

class _BMRState extends State<BMR> with Trans {
  double bmr = 0;

  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  KeyboardActionsConfig _buildConfig(BuildContext context) {
    return KeyboardActionsConfig(
      keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
      keyboardBarColor: Colors.grey[200],
      keyboardSeparatorColor: Colors.black26,
      nextFocus: true,
      actions: [
        KeyboardActionsItem(focusNode: _nodeText3, toolbarButtons: [
          (node) {
            return GestureDetector(
              onTap: () => node.unfocus(),
              child: Container(
                padding: EdgeInsets.all(8.0),
                color: Colors.orange[500],
                child: Text(
                  AppLocalizations.of(context)!.translate("Done"),
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          }
        ]),
        KeyboardActionsItem(focusNode: _nodeText2, toolbarButtons: [
          (node) {
            return GestureDetector(
              onTap: () => node.unfocus(),
              child: Container(
                padding: EdgeInsets.all(8.0),
                color: Colors.orange[500],
                child: Text(
                  AppLocalizations.of(context)!.translate("Done"),
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          }
        ]),
        KeyboardActionsItem(
          focusNode: _nodeText1,
          toolbarButtons: [
            //button 2
            (node) {
              return GestureDetector(
                onTap: () => node.unfocus(),
                child: Container(
                  color: Colors.orange,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    AppLocalizations.of(context)!.translate("Done"),
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              );
            }
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    setContext(context);
    return Form(
        child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: AppBarNav(depth: 1),
            body: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('asset/image/WT_black_background.jpg'),
                    fit: BoxFit.fill,
                    alignment: Alignment.center,
                  ),
                ),
                child: KeyboardActions(
                    config: _buildConfig(context),
                    child: SingleChildScrollView(
                        padding: EdgeInsets.only(top: 100),
                        child:
                            Column(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [
                          getWeightInput(),
                          getFitnessLevel(),
                          Divider(),
                          Container(
                            padding: EdgeInsets.only(left: 35, right: 35),
                            child: Text(t("Resting Metabolic Rate"),
                                textAlign: TextAlign.center,
                                style: GoogleFonts.archivoBlack(
                                  shadows: <Shadow>[
                                    Shadow(
                                      offset: Offset(5.0, 5.0),
                                      blurRadius: 3.0,
                                      color: Colors.black54,
                                    ),
                                  ],
                                  fontSize: 24,
                                  color: Colors.orange[300],
                                )),
                          ),
                          Text(widget.exerciseBloc.bmrEnergy.toStringAsFixed(0) + " kCal",
                              style: GoogleFonts.archivoBlack(
                                shadows: <Shadow>[
                                  Shadow(
                                    offset: Offset(5.0, 5.0),
                                    blurRadius: 3.0,
                                    color: Colors.black54,
                                  ),
                                ],
                                fontSize: 30,
                                color: Colors.orange[300],
                              )),
                          Container(
                            padding: EdgeInsets.only(left: 65, right: 65),
                            alignment: Alignment.center,
                            child:
                                Text(t("Resting metabolic rate is the rate at which your body burns energy when it is at complete rest."),
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.inter(
                                      fontSize: 16,
                                      color: Colors.yellow[200],
                                    )),
                          ),
                          SizedBox(height: 20),
                          Container(
                            padding: EdgeInsets.only(left: 35, right: 35),
                            child: Text(t("Basal Metabolic Rate"),
                                textAlign: TextAlign.center,
                                style: GoogleFonts.archivoBlack(
                                  shadows: <Shadow>[
                                    Shadow(
                                      offset: Offset(5.0, 5.0),
                                      blurRadius: 3.0,
                                      color: Colors.black54,
                                    ),
                                  ],
                                  fontSize: 24,
                                  color: Colors.orange[500],
                                )),
                          ),
                          Text(widget.exerciseBloc.getBMR().toStringAsFixed(0) + " kCal",
                              style: GoogleFonts.archivoBlack(
                                shadows: <Shadow>[
                                  Shadow(
                                    offset: Offset(5.0, 5.0),
                                    blurRadius: 3.0,
                                    color: Colors.black54,
                                  ),
                                ],
                                fontSize: 30,
                                color: Colors.orange[500],
                              )),
                          Container(
                            padding: EdgeInsets.only(left: 65, right: 65),
                            alignment: Alignment.center,
                            child: Text(t("Based on your weight, height and activity your BMR value"),
                                textAlign: TextAlign.center,
                                style: GoogleFonts.inter(
                                  fontSize: 16,
                                  color: Colors.yellow[200],
                                )),
                          ),
                        ]))))));
  }

  Widget getHeightInput() {
    int birthYear =
        widget.exerciseBloc.customerRepository.customer != null && widget.exerciseBloc.customerRepository.customer!.birthYear != null
            ? widget.exerciseBloc.customerRepository.customer!.birthYear!
            : 0;
    double height = widget.exerciseBloc.height != null ? widget.exerciseBloc.height! : 0;
    if (birthYear < 2003) {
      return Flexible(
        child: TextFormField(
            focusNode: _nodeText2,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5),
              labelText: AppLocalizations.of(context)!.translate("Actual Height"),
              labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]),
              fillColor: Colors.black38,
              filled: true,
              border: OutlineInputBorder(
                gapPadding: 4.0,
                borderRadius: BorderRadius.circular(12.0),
                borderSide: BorderSide(color: Colors.white12, width: 0.4),
              ),
            ),
            initialValue: height.toStringAsFixed(0),
            keyboardType: TextInputType.numberWithOptions(decimal: false),
            textInputAction: TextInputAction.done,
            style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.yellow[300]),
            onChanged: (value) => {
                  if (value.isNotEmpty)
                    {
                      value = value.replaceFirst(",", "."),
                      value = value.replaceAll(RegExp(r'[^0-9.]'), ""),
                      widget.exerciseBloc.add(ExerciseNewHeightChange(value: double.parse(value))),
                    }
                }),
      );
    } else {
      return Container();
    }
  }

  Widget getBirthyearInput() {
    int birthYear = widget.exerciseBloc.birthYear != null ? widget.exerciseBloc.birthYear! : 0;
    return Flexible(
      child: TextFormField(
          focusNode: _nodeText3,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5),
            labelText: AppLocalizations.of(context)!.translate("Birth Year"),
            labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]),
            fillColor: Colors.black38,
            filled: true,
            border: OutlineInputBorder(
              gapPadding: 4.0,
              borderRadius: BorderRadius.circular(12.0),
              borderSide: BorderSide(color: Colors.white12, width: 0.4),
            ),
          ),
          initialValue: birthYear.toStringAsFixed(0),
          keyboardType: TextInputType.numberWithOptions(decimal: false),
          textInputAction: TextInputAction.done,
          style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.yellow[300]),
          onChanged: (value) => {
                if (value.isNotEmpty)
                  {
                    value = value.replaceAll(RegExp(r'[^0-9.]'), ""),
                    widget.exerciseBloc.add(ExerciseNewBirthyearChange(value: int.parse(value)))
                  }
              }),
    );
  }

  Widget getFitnessLevel() {
    String? fitnessLevel = widget.exerciseBloc.fitnessLevel;
    if (fitnessLevel == null) {
      return Container();
    }
    return Container(
        padding: EdgeInsets.only(left: 65, right: 65),
        child: DropdownSearch<FitnessState>(
          dropdownSearchDecoration: InputDecoration(
            contentPadding: EdgeInsets.only(left: 15, top: 5, bottom: 5),
            labelText: t("Fitness Activity"),
            labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]),
            fillColor: Colors.black38,
            filled: true,
            border: OutlineInputBorder(
              gapPadding: 2.0,
              borderRadius: BorderRadius.circular(12.0),
              borderSide: BorderSide(color: Colors.white12, width: 0.4),
            ),
          ),
          mode: Mode.MENU,
          compareFn: (FitnessState? i, FitnessState? s) => i!.isEqual(s),
          showSelectedItem: true,
          selectedItem: FitnessItem().getItem(fitnessLevel),
          itemAsString: (data) => t(data!.stateText),
          onChanged: (data) {
            widget.exerciseBloc.add(ExerciseNewFitnessLevelChange(value: data!.value));
          },
          dropdownBuilder: _customDropDownItem,
          popupItemBuilder: _customMenuBuilder,
          items: FitnessItem().toList(),
          dropDownButton: Icon(
            Icons.arrow_drop_down,
            color: Colors.yellow[200],
          ),
        ));
  }

  Widget _customMenuBuilder(BuildContext context, FitnessState? item, bool isSelected) {
    bool selected = item!.value == widget.exerciseBloc.fitnessLevel;
    return Container(
      decoration: !selected
          ? BoxDecoration(color: Colors.black54)
          : BoxDecoration(
              border: Border.all(color: Colors.blue),
              borderRadius: BorderRadius.circular(5),
              color: Colors.black38,
            ),
      child: ListTile(
        selected: selected,
        title: Text(
          t(item.stateText),
          style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.yellow[300]),
        ),
        subtitle: Text(
          t(item.explanation),
          style: GoogleFonts.inter(fontSize: 12, color: Colors.yellow[300]),
        ),
      ),
    );
  }

  Widget _customDropDownItem(BuildContext context, FitnessState? item, String itemDesignation) {
    return Container(
      child: (item == null)
          ? ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                t("No item selected"),
                style: GoogleFonts.inter(fontSize: 14, color: Colors.yellow[300]),
              ),
            )
          : ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                t(item.stateText),
                style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.yellow[300]),
              ),
              subtitle: Text(
                t(item.explanation),
                style: GoogleFonts.inter(fontSize: 12, color: Colors.yellow[300]),
              ),
            ),
    );
  }

  Widget getWeightInput() {
    double weight = widget.exerciseBloc.weight != null ? widget.exerciseBloc.weight! : 0;
    return Container(
        padding: EdgeInsets.only(top: 15, left: 35, right: 35, bottom: 10),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            getBirthyearInput(),
            SizedBox(
              width: 5,
            ),
            getHeightInput(),
            SizedBox(
              width: 5,
            ),
            Flexible(
              child: TextFormField(
                focusNode: _nodeText1,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5),
                  labelText: AppLocalizations.of(context)!.translate("Actual Weight"),
                  labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]),
                  fillColor: Colors.black38,
                  filled: true,
                  border: OutlineInputBorder(
                    gapPadding: 2.0,
                    borderRadius: BorderRadius.circular(12.0),
                    borderSide: BorderSide(color: Colors.white12, width: 0.4),
                  ),
                ),
                initialValue: weight.toStringAsFixed(1),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                textInputAction: TextInputAction.done,
                style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.yellow[300]),
                onChanged: (value) => {
                  if (value.isNotEmpty)
                    {
                      value = value.replaceFirst(",", "."),
                      value = value.replaceAll(RegExp(r'[^0-9.]'), ""),
                      widget.exerciseBloc.add(ExerciseNewWeightChange(value: double.parse(value))),
                    }
                },
              ),
            ),
            IconButton(
                icon: Icon(Icons.save),
                hoverColor: Colors.blueAccent,
                color: widget.exerciseBloc.changedWeight ? Colors.blue[200] : Colors.black54,
                onPressed: () => {widget.exerciseBloc.add(ExerciseNewSaveWeight())})
          ],
        ));
  }
}