import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/H2O/insert_user_activity_request_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/H2O_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/ConfirmWithMessageDialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wave/config.dart';
import 'package:wave/wave.dart';

class TodayPage extends StatefulWidget {
  TodayPage({Key key}) : super(key: key);

  @override
  _TodayPageState createState() {
    return _TodayPageState();
  }
}

class _TodayPageState extends State<TodayPage> {
  TextEditingController _h20AmountController = TextEditingController();

  bool isUnitML = true;
  Future<bool> readPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    isUnitML = (prefs.getString(H2O_UNIT) ?? "ml") == "ml" ? true : false;
    return isUnitML;
  }

  bool canShowAddButton = false;

  @override
  Widget build(BuildContext context) {
    return BaseView<H2OViewModel>(
      onModelReady: (model) => model.getUserProgressForTodayData(),
      builder: (_, model, widget) => AppScaffold(
        isShowAppBar: false,
        appBarTitle: TranslationBase.of(context).h2o,
        baseViewModel: model,
        body: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          padding: EdgeInsets.all(21),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 320,
                child: Row(
                  children: [
                    Expanded(
                      child: FutureBuilder<bool>(
                        future: readPrefs(),
                        builder: (context, data) {
                          String unit;
                          if (data.connectionState == ConnectionState.done) {
                            isUnitML = data.data;
                          }
                          if (isUnitML) {
                            unit = TranslationBase.of(context).ml;
                          } else {
                            unit = TranslationBase.of(context).l;
                          }
                          unit = unit.toLowerCase();
                          double totalH2O = model?.userProgressData?.quantityLimit ?? 0.0;
                          double consumedH2O = model?.userProgressData?.quantityConsumed ?? 0.0;
                          if (!isUnitML) {
                            totalH2O = totalH2O / 1000;
                            consumedH2O = consumedH2O / 1000;
                          }

                          if (consumedH2O > totalH2O) {
                            consumedH2O = totalH2O;
                          }

                          double divide = consumedH2O / totalH2O;
                          String percentage = (divide * 100).toStringAsFixed(0);
                          var remainingH2O = totalH2O - consumedH2O;

                          return AspectRatio(
                            aspectRatio: 234 / 320,
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(18),
                                  child: WaveWidget(
                                    config: CustomConfig(
                                      colors: [Color(0xff0d47a1), Color(0xff1976d2), Color(0xff2196f3)],
                                      durations: [19440, 10800, 6000],
                                      heightPercentages: [1 - divide - .10, 1 - divide - .05, 1 - divide],
                                      blur: MaskFilter.blur(BlurStyle.solid, 0),
                                    ),
                                    waveAmplitude: 0,
                                    backgroundColor: Color(0xff2e303a),
                                    size: Size(
                                      double.infinity,
                                      double.infinity,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(top: 12, bottom: 12),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        remainingH2O.toStringAsFixed(0) + "$unit " + TranslationBase.of(context).left.toLowerCase(),
                                        style: TextStyle(
                                          fontSize: 14,
                                          fontWeight: FontWeight.w600,
                                          color: Colors.white,
                                          letterSpacing: -0.56,
                                        ),
                                      ),
                                      Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Text(
                                            "$percentage%",
                                            style: TextStyle(
                                              fontSize: 34,
                                              fontWeight: FontWeight.bold,
                                              color: Colors.white,
                                              letterSpacing: -2.34,
                                            ),
                                          ),
                                          Text(
                                            TranslationBase.of(context).consumed,
                                            style: TextStyle(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                              color: Colors.white,
                                              letterSpacing: -0.56,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                    SizedBox(width: 21),
                    SizedBox(
                      height: double.infinity,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          _circularButton(context, 600, model),
                          SizedBox(height: 8),
                          _circularButton(context, 330, model),
                          SizedBox(height: 8),
                          _circularButton(context, 200, model),
                          SizedBox(height: 8),
                          InkWell(
                            onTap: () => undoVolume(context, model),
                            child: Text(
                              TranslationBase.of(context).undo,
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: Color(0xffD02127),
                                letterSpacing: -0.56,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 40),
              Text(
                TranslationBase.of(context).addCustomAmount,
                style: TextStyle(
                  fontSize: 14,
                  height: 21 / 14,
                  fontWeight: FontWeight.w600,
                  color: Color(0xff2B353E),
                  letterSpacing: -0.56,
                ),
              ),
              SizedBox(height: 12),
              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: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                TranslationBase.of(context).amount_,
                                style: TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xff2E303A),
                                  letterSpacing: -0.44,
                                ),
                              ),
                              TextField(
                                controller: _h20AmountController,
                                keyboardType: TextInputType.number,
                                onChanged: (value) {
                                  double _value = 0;
                                  if (value.length > 0) _value = double.parse(value);

                                  if (value.length > 0) {
                                    if (canShowAddButton) {
                                      return;
                                    }
                                    canShowAddButton = true;
                                    setState(() {});
                                  } else {
                                    canShowAddButton = false;
                                    setState(() {});
                                  }
                                },
                                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,
                                ),
                              ),
                            ],
                          ),
                        ),
                        if (canShowAddButton)
                          Expanded(
                            flex: 1,
                            child: DefaultButton(
                              TranslationBase.of(context).add,
                              () async {
                                await showConfirmMessage(context, int.parse(_h20AmountController.text), model);
                                _h20AmountController.text = "";
                                canShowAddButton = false;
                                SystemChannels.textInput.invokeMethod('TextInput.hide');
                                setState(() {});
                              },
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _circularButton(context, int value, model) {
    String _text = "$value${TranslationBase.of(context).ml}";
    return InkWell(
      onTap: () {
        showConfirmMessage(context, value, model);
      },
      child: Container(
        padding: EdgeInsets.all(21),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
          border: Border.all(width: 1, color: Color(0xffDEDEDE)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              TranslationBase.of(context).add,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: Color(0xff575757),
                letterSpacing: -0.44,
              ),
            ),
            Text(
              _text,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Color(0xff2E303A),
                letterSpacing: -0.56,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future showConfirmMessage(context, int amount, H2OViewModel model) async {
    String title = "${TranslationBase.of(context).areyousure} $amount ${(isUnitML ? TranslationBase.of(context).ml : TranslationBase.of(context).l).toLowerCase()} ?";
    await showDialog(
      context: context,
      builder: (cxt) => ConfirmWithMessageDialog(
        message: title,
        onTap: () async {
          GifLoaderDialogUtils.showMyDialog(context);
          InsertUserActivityRequestModel insertUserActivityRequestModel = InsertUserActivityRequestModel(quantityIntake: amount);
          await model.insertUserActivity(insertUserActivityRequestModel);
          GifLoaderDialogUtils.hideDialog(context);
          FocusManager.instance.primaryFocus.unfocus();
        },
      ),
    );
  }

  void undoVolume(context, H2OViewModel model) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.undoUserActivity();
    GifLoaderDialogUtils.hideDialog(context);
  }
}
