import 'dart:async';

import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/models/auth/check_activation_code_request_model.dart';
import 'package:doctor_app_flutter/models/doctor/clinic_model.dart';
import 'package:doctor_app_flutter/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/doctor/profile_req_Model.dart';
import 'package:doctor_app_flutter/widgets/auth/show_timer_text.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

import '../../config/size_config.dart';
import '../../core/viewModel/auth_view_model.dart';
import '../../routes.dart';
import '../../util/dr_app_shared_pref.dart';
import '../../util/dr_app_toast_msg.dart';
import '../../util/helpers.dart';
import '../../widgets/shared/dr_app_circular_progress_Indeicator.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
Helpers helpers = Helpers();

class VerifyAccount extends StatefulWidget {
  VerifyAccount({this.changeLoadingStata});

  final Function changeLoadingStata;

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

class _VerifyAccountState extends State<VerifyAccount> {
  final verifyAccountForm = GlobalKey<FormState>();
  Map verifyAccountFormValue = {
    'digit1': null,
    'digit2': null,
    'digit3': null,
    'digit4': null,
  };
  Future _loggedUserFuture;
  var _loggedUser;
  AuthViewModel authProv;
  bool _isInit = true;
  var model;
  TextEditingController digit1 = TextEditingController(text: "");
  TextEditingController digit2 = TextEditingController(text: "");
  TextEditingController digit3 = TextEditingController(text: "");
  TextEditingController digit4 = TextEditingController(text: "");

  @override
  void initState() {
    super.initState();
    _loggedUserFuture = getSharedPref();
  }

  Future<void> getSharedPref() async {
    sharedPref.getObj(LOGGED_IN_USER).then((userInfo) {
      _loggedUser = userInfo;
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_isInit) {
      authProv = Provider.of<AuthViewModel>(context);
      final routeArgs = ModalRoute.of(context).settings.arguments as Map;
      model = routeArgs['model'];
    }
    _isInit = false;
  }

  @override
  Widget build(BuildContext context) {
    authProv = Provider.of<AuthViewModel>(context);
    final focusD1 = FocusNode();
    final focusD2 = FocusNode();
    final focusD3 = FocusNode();
    final focusD4 = FocusNode();
    return FutureBuilder(
        future: Future.wait([_loggedUserFuture]),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return DrAppCircularProgressIndeicator();
            default:
              if (snapshot.hasError) {
                DrAppToastMsg.showErrorToast('Error: ${snapshot.error}');
                return Text('Error: ${snapshot.error}');
              } else {
                return Form(
                    key: verifyAccountForm,
                    child: Container(
                        width: SizeConfig.realScreenWidth * 0.90,
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              buildSizedBox(30),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: <Widget>[
                                  Container(
                                    width: SizeConfig.realScreenWidth * 0.20,
                                    child: TextFormField(
                                      textInputAction: TextInputAction.next,
                                      style: buildTextStyle(),
                                      autofocus: true,
                                      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: SizeConfig.realScreenWidth * 0.20,
                                    child: TextFormField(
                                        focusNode: focusD2,
                                        controller: digit2,
                                        textInputAction: TextInputAction.next,
                                        maxLength: 1,
                                        textAlign: TextAlign.center,
                                        style: buildTextStyle(),
                                        keyboardType: TextInputType.number,
                                        decoration:
                                            buildInputDecoration(context),
                                        onSaved: (val) {
                                          verifyAccountFormValue['digit2'] =
                                              val;
                                        },
                                        onFieldSubmitted: (_) {
                                          FocusScope.of(context)
                                              .requestFocus(focusD3);
                                        },
                                        onChanged: (val) {
                                          if (val.length == 1) {
                                            FocusScope.of(context)
                                                .requestFocus(focusD3);
                                          }
                                        },
                                        validator: validateCodeDigit),
                                  ),
                                  Container(
                                      width: SizeConfig.realScreenWidth * 0.20,
                                      child: TextFormField(
                                          focusNode: focusD3,
                                          controller: digit3,
                                          textInputAction: TextInputAction.next,
                                          maxLength: 1,
                                          textAlign: TextAlign.center,
                                          style: buildTextStyle(),
                                          keyboardType: TextInputType.number,
                                          decoration:
                                              buildInputDecoration(context),
                                          onSaved: (val) {
                                            verifyAccountFormValue['digit3'] =
                                                val;
                                          },
                                          onFieldSubmitted: (_) {
                                            FocusScope.of(context)
                                                .requestFocus(focusD4);
                                          },
                                          onChanged: (val) {
                                            if (val.length == 1) {
                                              FocusScope.of(context)
                                                  .requestFocus(focusD4);
                                            }
                                          },
                                          validator: validateCodeDigit)),
                                  Container(
                                      width: SizeConfig.realScreenWidth * 0.20,
                                      child: TextFormField(
                                          focusNode: focusD4,
                                          controller: digit4,
                                          maxLength: 1,
                                          textAlign: TextAlign.center,
                                          style: buildTextStyle(),
                                          keyboardType: TextInputType.number,
                                          decoration:
                                              buildInputDecoration(context),
                                          onSaved: (val) {
                                            verifyAccountFormValue['digit4'] =
                                                val;
                                          },
                                          validator: validateCodeDigit))
                                ],
                              ),
                              buildSizedBox(20),
                              buildText(),
                              buildSizedBox(40),
                              RaisedButton(
                                onPressed: () {
                                  verifyAccount(
                                      authProv, widget.changeLoadingStata);
                                },
                                elevation: 0.0,
                                child: Container(
                                  width: double.infinity,
                                  height: 50,
                                  child: Center(
                                    child: Text(
                                      TranslationBase.of(context).verify,
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize:
                                              3 * SizeConfig.textMultiplier),
                                    ),
                                  ),
                                ),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10),
                                    side: BorderSide(
                                        width: 0.5,
                                        color: HexColor('#CCCCCC'))),
                              ),
                              buildSizedBox(20),
                              ShowTimerText(model: model),
                              buildSizedBox(10),
                            ])));
              }
          }
        });
  }

/*
 *@author: Elham Rababah
 *@Date:19/4/2020
 *@param:
 *@return:
 *@desc:   change the style for the input field
 */
  TextStyle buildTextStyle() {
    return TextStyle(
      fontSize: SizeConfig.textMultiplier * 3,
    );
  }

  String validateCodeDigit(value) {
    if (value.isEmpty) {
      return 'Please enter your Password';
    }

    return null;
  }

/*
 *@author: Elham Rababah
 *@Date:28/4/2020
 *@param: context
 *@return:InputDecoration
 *@desc:   buildInputDecoration
 */
  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      // ts/images/password_icon.png
      contentPadding: EdgeInsets.only(top: 30, bottom: 30),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        borderSide: BorderSide(color: Colors.black),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).primaryColor),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
    );
  }

/*
 *@author: Elham Rababah
 *@Date:28/4/2020
 *@param:
 *@return: RichText
 *@desc:   buildText
 */
  RichText buildText() {
    String medthodName;
    switch (model['OTP_SendType']) {
      case 1:
        medthodName = TranslationBase.of(context).smsBy;
        break;
      case 2:
        medthodName = TranslationBase.of(context).whatsAppBy;
        break;
      default:
    }
    var text = RichText(
        text: new TextSpan(
            style: new TextStyle(
                fontSize: 3.0 * SizeConfig.textMultiplier, color: Colors.black),
            children: <TextSpan>[
          new TextSpan(text: TranslationBase.of(context).youWillReceiveA),
          new TextSpan(
              text: TranslationBase.of(context).loginCode,
              style: TextStyle(fontWeight: FontWeight.w700)),
          new TextSpan(text: ' ${medthodName},'),
          TextSpan(text: TranslationBase.of(context).pleaseEnterTheCode)
        ]));
    return text;
  }

  SizedBox buildSizedBox([double height = 20]) {
    return SizedBox(
      height: height,
    );
  }

/*
 *@author: Elham Rababah
 *@Date:15/4/2020
 *@param: authProv
 *@return:
 *@desc:   verify Account func call sendActivationCodeByOtpNotificationType service
 */
  verifyAccount(AuthViewModel authProv, Function changeLoadingStata) async {
    if (verifyAccountForm.currentState.validate()) {
      changeLoadingStata(true);

      verifyAccountForm.currentState.save();
      final activationCode = verifyAccountFormValue['digit1'] +
          verifyAccountFormValue['digit2'] +
          verifyAccountFormValue['digit3'] +
          verifyAccountFormValue['digit4'];

      int projectID = await sharedPref.getInt(PROJECT_ID);

      Map<String, dynamic> model = {
        "activationCode": activationCode,
        "DoctorID": _loggedUser['DoctorID'],
        "LogInTokenID": _loggedUser['LogInTokenID'],
        "ProjectID": projectID,
        "LanguageID": 2,
        "stamp": "2020-02-26T14:48:27.221Z",
        "IPAdress": "11.11.11.11",
        "VersionID": 1.2,
        "Channel": 9,
        "TokenID": "",
        "SessionID": "i1UJwCTSqt",
        "IsLoginForDoctorApp": true,
        "IsSilentLogIN": false
      };
      CheckActivationCodeRequestModel checkActivationCodeForDoctorApp =
          new CheckActivationCodeRequestModel(
              zipCode: _loggedUser['ZipCode'],
              mobileNumber: _loggedUser['MobileNumber'],
              projectID: await sharedPref.getInt(PROJECT_ID),
              logInTokenID: await sharedPref.getString(LOGIN_TOKEN_ID),
              activationCode: activationCode,
              generalid: "Cs2020@2016\$2958");

      authProv
          .checkActivationCodeForDoctorApp(checkActivationCodeForDoctorApp)
          .then((res) async {
        if (res['MessageStatus'] == 1) {
          sharedPref.setString(TOKEN, res['AuthenticationTokenID']);
          if (res['List_DoctorProfile'] != null) {
            loginProcessCompleted(
                res['List_DoctorProfile'][0], changeLoadingStata);
          } else {
            ClinicModel clinic =
                ClinicModel.fromJson(res['List_DoctorsClinic'][0]);
            getDocProfiles(clinic, changeLoadingStata);
          }
        } else {
          changeLoadingStata(false);
          helpers.showErrorToast(res['ErrorEndUserMessage']);
        }
      }).catchError((err) {
        changeLoadingStata(false);
        helpers.showErrorToast(err);
      });
    }
  }

  /*
 *@author: Elham Rababah
 *@Date:17/5/2020
 *@param: Map<String, dynamic> profile, Function changeLoadingStata
 *@return:
 *@desc:   loginProcessCompleted
 */
  loginProcessCompleted(
      Map<String, dynamic> profile, Function changeLoadingStata) {
    var doctor = DoctorProfileModel.fromJson(profile);
    authProv.setDoctorProfile(doctor);
    sharedPref.setObj(DOCTOR_PROFILE, profile);
    this.getDashboard(doctor, changeLoadingStata);
  }

  getDashboard(doctor, Function changeLoadingStata) {
    // authProv.getDashboard(doctor).then((value) {
    //   print(value);
    changeLoadingStata(false);
    // sharedPref.setObj(DASHBOARD_DATA, value);
    Navigator.of(context).pushReplacementNamed(HOME);
    // });
  }

  Future<dynamic> _asyncSimpleDialog(
      BuildContext context, List list, String txtKey,
      [String text = '']) async {
    return await showDialog<dynamic>(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: Text(text),
            children: list.map((value) {
              return SimpleDialogOption(
                onPressed: () {
                  Navigator.pop(context,
                      value); //here passing the index to be return on item selection
                },
                child: Text(value[txtKey]), //item value
              );
            }).toList(),
          );
        });
  }

  /*
 *@author: Elham Rababah 
 *@Date:17/5/2020
 *@param: ClinicModel clinicInfo, Function changeLoadingStata
 *@return:
 *@desc:   getDocProfiles
 */
  getDocProfiles(ClinicModel clinicInfo, Function changeLoadingStata) {
    ProfileReqModel docInfo = new ProfileReqModel(
        doctorID: clinicInfo.doctorID,
        clinicID: clinicInfo.clinicID,
        license: true,
        projectID: clinicInfo.projectID,
        tokenID: '',
        languageID: 2);
    authProv.getDocProfiles(docInfo.toJson()).then((res) {
      if (res['MessageStatus'] == 1) {
        loginProcessCompleted(res['DoctorProfileList'][0], changeLoadingStata);
      } else {
        changeLoadingStata(false);
        helpers.showErrorToast(res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      changeLoadingStata(false);
      helpers.showErrorToast(err);
    });
  }
}
