import 'dart:async';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/check_activation_code_for_e_referral_request_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/all_habib_medical_services/e_referral_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class EReferralConfirmSMSDialog extends StatefulWidget {
  final String phoneNumber;
  final Function onSucces;
  // final AdvanceModel advanceModel;
  // final PatientInfoAndMobileNumber patientInfoAndMobileNumber;
  // final String selectedPaymentMethod;

  const EReferralConfirmSMSDialog(
      {Key key,
      this.phoneNumber,
        this.onSucces
      // this.advanceModel,
      // this.selectedPaymentMethod,
      // this.patientInfoAndMobileNumber
  })
      : super(key: key);

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

class _EReferralConfirmSMSDialogState extends State<EReferralConfirmSMSDialog> {
  final verifyAccountForm = GlobalKey<FormState>();
  Map verifyAccountFormValue = {
    'digit1': null,
    'digit2': null,
    'digit3': null,
    'digit4': null,
  };

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

  String timerText = (TIMER_MIN - 1).toString() + ':59';
  int min = TIMER_MIN - 1;
  int sec = 59;
  Timer _timer;

  resendCode() {
    min = TIMER_MIN - 1;
    sec = 59;
    _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      if (min <= 0 && sec <= 0) {
        timer.cancel();
      } else {
        setState(() {
          sec = sec - 1;
          if (sec == 0 && min == 0) {
            Navigator.pop(context);
            min = 0;
            sec = 0;
          } else if (sec == 0) {
            min = min - 1;
            sec = 59;
          }
          timerText = min.toString() + ':' + sec.toString();
        });
      }
    });
  }

  FocusNode focusD1;
  FocusNode focusD2;
  FocusNode focusD3;
  FocusNode focusD4;

  @override
  void initState() {
    super.initState();
    resendCode();
    focusD1 = FocusNode();
    focusD2 = FocusNode();
    focusD3 = FocusNode();
    focusD4 = FocusNode();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<EReferralViewModel>(
      builder: (_, model, w) => Dialog(
        elevation: 0.6,
        child: Container(
          height: 520,
          child: ListView(
            children: [
              Container(
                width: double.infinity,
                height: 40,
                color: Colors.grey[700],
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                        flex: 4,
                        child: Center(
                            child: Texts(
                          'SMS',
                          color: Colors.white,
                          textAlign: TextAlign.center,
                        ))),
                    Expanded(
                      flex: 1,
                      child: InkWell(
                        onTap: () => Navigator.pop(context),
                        child: Container(
                            decoration: BoxDecoration(
                                shape: BoxShape.circle, color: Colors.white),
                            child: Icon(
                              Icons.clear,
                              color: Colors.grey[900],
                            )),
                      ),
                    )
                  ],
                ),
              ),
              Image.asset(
                'assets/images/login/103.png',
                height: MediaQuery.of(context).size.width * 0.25,
                width: MediaQuery.of(context).size.width * 0.25,
              ),
              SizedBox(
                height: 12,
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Texts(
                  TranslationBase.of(context).pleaseEnterTheVerificationCode +
                      '[${widget.phoneNumber}]',
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Form(
                key: verifyAccountForm,
                child: Container(
                  width: SizeConfig.realScreenWidth * 0.90,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      SizedBox(
                        height: 30,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          Container(
                            width: 65,
                            child: TextFormField(
                              textInputAction: TextInputAction.next,
                              style: TextStyle(
                                fontSize: SizeConfig.textMultiplier * 3,
                              ),
                              focusNode: focusD1,
                              maxLength: 1,
                              controller: digit1,
                              textAlign: TextAlign.center,
                              keyboardType: TextInputType.number,
                              decoration: buildInputDecoration(context),
                              onSaved: (val) {
                                verifyAccountFormValue['digit1'] = val;
                              },
                              validator: validateCodeDigit,
                              onFieldSubmitted: (_) {
                                FocusScope.of(context).requestFocus(focusD2);
                              },
                              onChanged: (val) {
                                if (val.length == 1) {
                                  FocusScope.of(context).requestFocus(focusD2);
                                }
                              },
                            ),
                          ),
                          Container(
                            width: 65,
                            child: TextFormField(
                              focusNode: focusD2,
                              controller: digit2,
                              textInputAction: TextInputAction.next,
                              maxLength: 1,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: SizeConfig.textMultiplier * 3,
                              ),
                              keyboardType: TextInputType.number,
                              decoration: buildInputDecoration(context),
                              validator: validateCodeDigit,
                              onSaved: (val) {
                                verifyAccountFormValue['digit2'] = val;
                              },
                              onFieldSubmitted: (_) {
                                FocusScope.of(context).requestFocus(focusD3);
                              },
                              onChanged: (val) {
                                if (val.length == 1) {
                                  FocusScope.of(context).requestFocus(focusD3);
                                }
                              },
                            ),
                          ),
                          Container(
                              width: 65,
                              child: TextFormField(
                                focusNode: focusD3,
                                controller: digit3,
                                textInputAction: TextInputAction.next,
                                maxLength: 1,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: SizeConfig.textMultiplier * 3,
                                ),
                                keyboardType: TextInputType.number,
                                decoration: buildInputDecoration(context),
                                validator: validateCodeDigit,
                                onSaved: (val) {
                                  verifyAccountFormValue['digit3'] = val;
                                },
                                onFieldSubmitted: (_) {
                                  FocusScope.of(context).requestFocus(focusD4);
                                },
                                onChanged: (val) {
                                  if (val.length == 1) {
                                    FocusScope.of(context)
                                        .requestFocus(focusD4);
                                  }
                                },
                              )),
                          Container(
                            width: 65,
                            child: TextFormField(
                                focusNode: focusD4,
                                controller: digit4,
                                maxLength: 1,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: SizeConfig.textMultiplier * 3,
                                ),
                                keyboardType: TextInputType.number,
                                decoration: buildInputDecoration(context),
                                validator: validateCodeDigit,
                                onSaved: (val) {
                                  verifyAccountFormValue['digit4'] = val;
                                },
                                onFieldSubmitted: (_) {
                                  FocusScope.of(context).requestFocus(focusD4);
                                  submit(model);
                                },
                                onChanged: (val) {
                                  if (val.length == 1) {
                                    FocusScope.of(context)
                                        .requestFocus(focusD4);
                                    submit(model);
                                  }
                                }),
                          )
                        ],
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      if (model.state == ViewState.ErrorLocal ||
                          model.state == ViewState.Error)
                        Container(
                          margin: EdgeInsets.only(left: 8, right: 8),
                          width: double.maxFinite,
                          child: Texts(
                            model.error,
                            color: Colors.red,
                          ),
                        ),
                      SizedBox(height: 20),
                      // buildText(),

                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Texts(
                          TranslationBase.of(context)
                                  .theVerificationCodeExpiresIn +
                              ' $timerText',
                          textAlign: TextAlign.center,
                        ),
                      ),
                      SizedBox(height: 20),

                      Container(
                        width: double.maxFinite,
                        padding: EdgeInsets.all(12),
                        child: SecondaryButton(
                          textColor: Colors.white,
                          label:
                              TranslationBase.of(context).submit.toUpperCase(),
                          onTap: () {
                            submit(model);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void submit(EReferralViewModel model) async {
    if (verifyAccountForm.currentState.validate()) {
      final activationCode =
          digit1.text + digit2.text + digit3.text + digit4.text;
      // ToDo call service
      CheckActivationCodeForEReferralResponseModel checkActivationCodeForEReferralRequestModel= new CheckActivationCodeForEReferralResponseModel(activationCode: activationCode);
      await model.checkActivationCodeForEReferral(checkActivationCodeForEReferralRequestModel);
      if(model.state == ViewState.ErrorLocal) {
        // Utils.showErrorToast(model.error);
      } else {
         widget.onSucces();
        // Navigator.push(context, FadePage(page: StartIndexForAddProduct()));
        // Navigate to new page
      }
    }
  }

  String validateCodeDigit(value) {
    if (value.isEmpty) {
      return '';
    }
    return null;
  }

  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      // ts/images/password_icon.png
      contentPadding: EdgeInsets.only(top: 20, bottom: 20),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(5)),
        borderSide: BorderSide(color: Colors.black),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        borderSide: BorderSide(color: Theme.of(context).primaryColor),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
    );
  }
}
