import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart';
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 'package:provider/provider.dart';

import 'carbs_result_page.dart';

class Carbs extends StatefulWidget {
  @override
  _CarbsState createState() => _CarbsState();
}

class _CarbsState extends State<Carbs> {
  TextEditingController textController = new TextEditingController();
  final GlobalKey clinicDropdownKey = GlobalKey();
  int calories;
  String dropdownValue;
  bool _visible = false;
  int meals;
  int protein;
  int carbs;

  int fat;
  double pCal;
  double cCal;
  double fCal;
  double pCalGram;
  double cCalGram;
  double fCalGram;
  double pCalMeal;
  double cCalMeal;
  double fCalMeal;

  void calculateDietRatios() {
    if (dropdownValue == TranslationBase.of(context).dietVeryLow) {
      meals = 3;
      protein = 45;
      carbs = 10;
      fat = 45;
    } else if (dropdownValue == TranslationBase.of(context).dietLow) {
      meals = 3;
      protein = 40;
      carbs = 30;
      fat = 30;
    } else if (dropdownValue == TranslationBase.of(context).dietModerate) {
      meals = 3;
      protein = 25;
      carbs = 50;
      fat = 25;
    } else if (dropdownValue == TranslationBase.of(context).dietUSDA) {
      meals = 3;
      protein = 15;
      carbs = 55;
      fat = 30;
    } else if (dropdownValue == TranslationBase.of(context).dietZone) {
      meals = 3;
      protein = 30;
      carbs = 40;
      fat = 30;
    }
  }

  void calculate() {
    pCal = (protein / 100.0) * int.parse(textController.text).ceil();
    cCal = (carbs / 100.0) * int.parse(textController.text);

    fCal = (fat / 100) * int.parse(textController.text);

    pCalGram = pCal / 4.0;
    cCalGram = cCal / 4.0;
    fCalGram = fCal / 9.0;
    pCalMeal = pCalGram / meals.ceil();
    cCalMeal = cCalGram / meals.ceil();
    fCalMeal = fCalGram / meals.ceil();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      appBarTitle: TranslationBase.of(context).carbohydrate,
      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(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      TranslationBase.of(context).carbProteinDesc,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.56,
                        color: CustomColors.textColor,
                      ),
                    ),
                    SizedBox(
                      height: 15.0,
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        inputWidget(TranslationBase.of(context).calDay, "0", textController),
                        InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              FadePage(page: CalorieCalculator()),
                            );
                          },
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Text(
                              TranslationBase.of(context).notSure,
                              style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.accentColor, decoration: TextDecoration.underline),
                            ),
                          ),
                        )
                      ],
                    ),
                    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).selectDiet,
                                    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;
                                            calculateDietRatios();
                                          });
                                        },
                                        items: <String>[
                                          TranslationBase.of(context).dietVeryLow,
                                          TranslationBase.of(context).dietLow,
                                          TranslationBase.of(context).dietModerate,
                                          TranslationBase.of(context).dietUSDA,
                                          TranslationBase.of(context).dietZone
                                        ].map<DropdownMenuItem<String>>((String value) {
                                          return DropdownMenuItem<String>(
                                            value: value,
                                            child: Text(value, style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)),
                                          );
                                        }).toList(),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(Icons.keyboard_arrow_down),
                          ],
                        ),
                      ).withBorderedContainer,
                    ),
                    SizedBox(
                      height: 25.0,
                    ),
                    SizedBox(
                      height: 55.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(() {
                  {
                    calculate();
                    Navigator.push(
                      context,
                      FadePage(
                          page: CarbsResult(
                        cCal: cCal,
                        pCal: pCal,
                        fCal: fCal,
                        pCalGram: pCalGram,
                        pCalMeal: pCalMeal,
                        fCalGram: fCalGram,
                        fCalMeal: fCalMeal,
                        cCalGram: cCalGram,
                        cCalMeal: cCalMeal,
                      )),
                    );
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  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),
        ],
      ),
    ),
  );
}

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,
      );
}
