import 'dart:async';

import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SMSOTP {
  final type;
  final mobileNo;
  final Function onSuccess;
  final Function onFailure;
  final context;

  int remainingTime = 600;

  Future<Null> timer;

  static BuildContext _context;

  static bool _loading;

  SMSOTP(
    this.context,
    this.type,
    this.mobileNo,
    this.onSuccess,
    this.onFailure,
  );

  final verifyAccountForm = GlobalKey<FormState>();

  TextEditingController digit1 = TextEditingController(text: "");
  TextEditingController digit2 = TextEditingController(text: "");
  TextEditingController digit3 = TextEditingController(text: "");
  TextEditingController digit4 = TextEditingController(text: "");

  Map verifyAccountFormValue = {
    'digit1': '',
    'digit2': '',
    'digit3': '',
    'digit4': '',
  };
  final focusD1 = FocusNode();
  final focusD2 = FocusNode();
  final focusD3 = FocusNode();
  final focusD4 = FocusNode();
  String errorMsg;
  ProjectViewModel projectProvider;
  String displayTime = '';
  bool isClosed = false;
  displayDialog(BuildContext context) async {
    return showDialog(
        context: context,
        barrierColor: Colors.black.withOpacity(0.7),
        builder: (context) {
          projectProvider = Provider.of(context);
          return AlertDialog(
            contentPadding: EdgeInsets.fromLTRB(24.0, 0.0, 0.0, 24.0),

            // shape: RoundedRectangleBorder(
            //     borderRadius: BorderRadius.all(Radius.circular(10.0))),
            content: StatefulBuilder(builder: (context, setState) {
              if (displayTime == '') {
                startTimer(setState);
              }
              return Container(
                color: Colors.white,
                height: SizeConfig.realScreenHeight * 0.5,
                width: SizeConfig.realScreenWidth * 0.8,
                child: Center(
                    child: SingleChildScrollView(
                        child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              type == 1
                                  ? Padding(
                                      child: Icon(
                                        DoctorApp.verify_sms_1,
                                        size: 50,
                                      ),
                                      padding: EdgeInsets.only(bottom: 20),
                                    )
                                  : Padding(
                                      child: Icon(
                                        DoctorApp.verify_whtsapp,
                                        size: 50,
                                      ),
                                      padding: EdgeInsets.only(bottom: 20),
                                    ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: <Widget>[
                                  Padding(
                                      padding: EdgeInsets.only(
                                          left: 10, right: 10, bottom: 20),
                                      child: IconButton(
                                        icon: Icon(Icons.close),
                                        iconSize: 40,
                                        onPressed: () {
                                          this.isClosed = true;
                                          Navigator.pop(context);
                                          this.onFailure();
                                        },
                                      ))
                                ],
                              )
                            ])),
                    Padding(
                        padding: EdgeInsets.only(top: 5, right: 5),
                        child: AppText(
                          TranslationBase.of(context).verificationMessage +
                              ' XXXXXX' +
                              mobileNo
                                  .toString()
                                  .substring(mobileNo.toString().length - 3),
                          textAlign: TextAlign.start,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                          maxLines: 2,
                        )),
                    Form(
                      key: verifyAccountForm,
                      child: Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Directionality(
                            textDirection: TextDirection.ltr,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Container(
                                  width: SizeConfig.realScreenWidth * 0.16,
                                  margin: EdgeInsets.all(5),
                                  child: TextFormField(
                                    textInputAction: TextInputAction.next,
                                    style: buildTextStyle(),
                                    autofocus: true,
                                    maxLength: 1,
                                    controller: digit1,
                                    textAlign: TextAlign.center,
                                    keyboardType: TextInputType.number,
                                    decoration: buildInputDecoration(context),
                                    onSaved: (val) {},
                                    validator: validateCodeDigit,
                                    onFieldSubmitted: (_) {
                                      FocusScope.of(context)
                                          .requestFocus(focusD2);
                                    },
                                    onChanged: (val) {
                                      if (val.length == 1) {
                                        FocusScope.of(context)
                                            .requestFocus(focusD2);
                                        verifyAccountFormValue['digit1'] =
                                            val.trim();
                                        checkValue();
                                      }
                                    },
                                  ),
                                ),
                                Container(
                                  width: SizeConfig.realScreenWidth * 0.16,
                                  margin: EdgeInsets.all(5),
                                  child: TextFormField(
                                      focusNode: focusD2,
                                      textInputAction: TextInputAction.next,
                                      maxLength: 1,
                                      controller: digit2,
                                      textAlign: TextAlign.center,
                                      style: buildTextStyle(),
                                      keyboardType: TextInputType.number,
                                      decoration: buildInputDecoration(context),
                                      onSaved: (val) {},
                                      onFieldSubmitted: (_) {
                                        FocusScope.of(context)
                                            .requestFocus(focusD3);
                                      },
                                      onChanged: (val) {
                                        if (val.length == 1) {
                                          FocusScope.of(context)
                                              .requestFocus(focusD3);
                                          verifyAccountFormValue['digit2'] =
                                              val.trim();
                                          checkValue();
                                        }
                                      },
                                      validator: validateCodeDigit),
                                ),
                                Container(
                                    margin: EdgeInsets.all(5),
                                    width: SizeConfig.realScreenWidth * 0.16,
                                    child: TextFormField(
                                        focusNode: focusD3,
                                        textInputAction: TextInputAction.next,
                                        maxLength: 1,
                                        controller: digit3,
                                        textAlign: TextAlign.center,
                                        style: buildTextStyle(),
                                        keyboardType: TextInputType.number,
                                        decoration:
                                            buildInputDecoration(context),
                                        onSaved: (val) {},
                                        onFieldSubmitted: (_) {
                                          FocusScope.of(context)
                                              .requestFocus(focusD4);
                                        },
                                        onChanged: (val) {
                                          if (val.length == 1) {
                                            FocusScope.of(context)
                                                .requestFocus(focusD4);
                                            verifyAccountFormValue['digit3'] =
                                                val.trim();
                                            checkValue();
                                          }
                                        },
                                        validator: validateCodeDigit)),
                                Container(
                                    margin: EdgeInsets.all(5),
                                    width: SizeConfig.realScreenWidth * 0.16,
                                    child: TextFormField(
                                        focusNode: focusD4,
                                        maxLength: 1,
                                        textAlign: TextAlign.center,
                                        style: buildTextStyle(),
                                        controller: digit4,
                                        keyboardType: TextInputType.number,
                                        decoration:
                                            buildInputDecoration(context),
                                        onFieldSubmitted: (_) {
                                          FocusScope.of(context)
                                              .requestFocus(focusD4);
                                        },
                                        onChanged: (val) {
                                          if (val.length == 1) {
                                            verifyAccountFormValue['digit4'] =
                                                val.trim();
                                            checkValue();
                                          }
                                        },
                                        validator: validateCodeDigit)),
                              ],
                            )),
                      ),
                    ),
                    Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AppText(
                            TranslationBase.of(context).validationMessage + ' ',
                            fontWeight: FontWeight.w600,
                            fontSize: 14,
                          ),
                          AppText(
                            displayTime,
                            color: Colors.red,
                            textAlign: TextAlign.start,
                            fontWeight: FontWeight.bold,
                            fontSize: 14,
                          )
                        ])
                  ],
                ))),
              );
            }),
          );
        });
  }

  TextStyle buildTextStyle() {
    return TextStyle(
      fontSize: SizeConfig.textMultiplier * 3,
    );
  }

  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      counterText: " ",
      // ts/images/password_icon.png
      // contentPadding: EdgeInsets.only(top: 20, bottom: 20),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        borderSide: BorderSide(color: Colors.grey[300]),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Colors.grey[300]),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Colors.grey[300]),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
    );
  }

  String validateCodeDigit(value) {
    if (value.isEmpty) {
      return ' ';
    } else if (value.length == 3) {
      print(value);
    } else {
      return null;
    }
  }

  checkValue() {
    //print(verifyAccountFormValue);
    if (verifyAccountForm.currentState.validate()) {
      onSuccess(digit1.text.toString() +
          digit2.text.toString() +
          digit3.text.toString() +
          digit4.text.toString());
    }
  }

  getSecondsAsDigitalClock(int inputSeconds) {
    var sec_num =
        int.parse(inputSeconds.toString()); // don't forget the second param
    var hours = (sec_num / 3600).floor();
    var minutes = ((sec_num - hours * 3600) / 60).floor();
    var seconds = sec_num - hours * 3600 - minutes * 60;
    var minutesString = "";
    var secondsString = "";
    minutesString =
        minutes < 10 ? "0" + minutes.toString() : minutes.toString();
    secondsString =
        seconds < 10 ? "0" + seconds.toString() : seconds.toString();
    return minutesString + ":" + secondsString;
  }

  startTimer(setState) {
    this.remainingTime--;
    setState(() {
      displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
    });

    timer = Future.delayed(Duration(seconds: 1), () {
      if (this.remainingTime > 0) {
        if (isClosed == false) startTimer(setState);
      } else {
        Navigator.pop(context);
      }
    });
  }

  static void showLoadingDialog(BuildContext context, bool _loading) async {
    _context = context;

    if (_loading == false) {
      Navigator.of(context).pop();
      return;
    }
    _loading = true;
    await showDialog(
        context: _context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return SimpleDialog(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            children: <Widget>[
              Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                ),
              )
            ],
          );
        });
  }

  static void hideSMSBox(context) {
    Navigator.pop(context);
  }
}
