import 'dart:io' show Platform;

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

import '../../config/size_config.dart';
import '../../providers/auth_provider.dart';
import '../../routes.dart';
import '../../util/dr_app_shared_pref.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();

/* 
 *@author: Elham Rababah 
 *@Date:4/7/2020
 *@param: 
 *@return:
 *@desc:   Verification Methods widget
 */
class VerificationMethods extends StatefulWidget {
  VerificationMethods({this.changeLoadingStata});
  final Function changeLoadingStata;
  @override
  _VerificationMethodsState createState() => _VerificationMethodsState();
}

class _VerificationMethodsState extends State<VerificationMethods> {
  MainAxisAlignment spaceBetweenMethods = MainAxisAlignment.spaceBetween;
  Future _loggedUserFuture;
  var _loggedUser;
  var verificationMethod;
  @override
  void initState() {
    super.initState();
    _loggedUserFuture = getSharedPref();
  }

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

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final routeArgs = ModalRoute.of(context).settings.arguments as Map;
    verificationMethod =
        routeArgs != null ? routeArgs['verificationMethod'] : null;
  }

  @override
  Widget build(BuildContext context) {
    AuthProvider authProv = Provider.of<AuthProvider>(context);
    return FutureBuilder(
        future: Future.wait([_loggedUserFuture]),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return DrAppCircularProgressIndeicator();
            default:
              if (snapshot.hasError) {
                helpers.showErrorToast('Error: ${snapshot.error}');
                return Text('Error: ${snapshot.error}');
              } else {
                return Container(
                  width: SizeConfig.realScreenWidth * 0.80,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        hideSilentMethods()
                            ? TranslationBase.of(context).firstStep
                            : TranslationBase.of(context).pleaseChoose,
                        style: TextStyle(
                          fontSize: 3.5 * SizeConfig.textMultiplier,
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Container(
                        height: SizeConfig.realScreenHeight * 0.6,
                        child: CustomScrollView(
                          primary: false,
                          slivers: <Widget>[
                            SliverPadding(
                              padding: const EdgeInsets.all(0),
                              sliver: SliverGrid.count(
                                // childAspectRatio: 0.7,
                                crossAxisSpacing: 0,
                                mainAxisSpacing: 5,
                                crossAxisCount: 2,
                                children: <Widget>[
                                  Visibility(
                                    visible: hideSilentMethods() ? false : true,
                                    child: buildFingerprintMethod(
                                        context, authProv),
                                    replacement:
                                        buildWhatsAppMethod(context, authProv),
                                  ),
                                  Visibility(
                                    visible: hideSilentMethods() ? false : true,
                                    child: buildFaceIDMethod(context, authProv),
                                    replacement:
                                        buildSMSMethod(context, authProv),
                                  ),
                                  Visibility(
                                      visible:
                                          hideSilentMethods() ? false : true,
                                      child: buildWhatsAppMethod(
                                          context, authProv)),
                                  Visibility(
                                    visible: hideSilentMethods() ? false : true,
                                    child: buildSMSMethod(context, authProv),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        // height: 500,
                      ),
                      SizedBox(
                          // height:  20,
                          )
                    ],
                  ),
                );
              }
          }
        });
  }

  /*
 *@author: Elham Rababah
 *@Date:28/5/2020
 *@param: BuildContext context, AuthProvider authProv
 *@return: Center widget
 *@desc:   buildSMSMethod Methods widget
 */
  Center buildSMSMethod(BuildContext context, AuthProvider authProv) {
    return buildVerificationMethod(
        context,
        'assets/images/verification_sms_icon.png',
        TranslationBase.of(context).sms, () {
      sendActivationCodeByOtpNotificationType(1, authProv);
    });
  }

  /*
 *@author: Elham Rababah
 *@Date:28/5/2020
 *@param: BuildContext context, AuthProvider authProv
 *@return: Center widget
 *@desc:   build WhatsApp  Methods widget
 */
  Center buildWhatsAppMethod(BuildContext context, AuthProvider authProv) {
    return buildVerificationMethod(
        context,
        'assets/images/verification_whatsapp_icon.png',
        TranslationBase.of(context).whatsApp, () {
      sendActivationCodeByOtpNotificationType(2, authProv);
    });
  }

/*
 *@author: Elham Rababah
 *@Date:28/5/2020
 *@param: BuildContext context, AuthProvider authProv
 *@return: Center widget
 *@desc:   build FaceID Methods widget
 */
  Center buildFaceIDMethod(BuildContext context, AuthProvider authProv) {
    return buildVerificationMethod(
        context,
        'assets/images/verification_faceid_icon.png',
        TranslationBase.of(context).faceId, () {
      sendActivationCodeByOtpNotificationType(3, authProv);
    });
  }

/*
 *@author: Elham Rababah
 *@Date:28/5/2020
 *@param: BuildContext context, AuthProvider authProv
 *@return: Center widget
 *@desc:   build Fingerprint Methods widget
 */
  Center buildFingerprintMethod(BuildContext context, AuthProvider authProv) {
    return buildVerificationMethod(
        context,
        'assets/images/verification_fingerprint_icon.png',
        TranslationBase.of(context).fingerprint, () {
      sendActivationCodeByOtpNotificationType(4, authProv);
    });
  }

  /*
 *@author: Elham Rababah
 *@Date:28/5/2020
 *@param: BuildContext context, AuthProvider authProv
 *@return: Center widget
 *@desc:   build Verification Methods widget
 */
  Center buildVerificationMethod(context, url, dec, Function fun) {
    return Center(
      child: InkWell(
        onTap: fun,
        child: Container(
          // height: SizeConfig.heightMultiplier *2,
          height: SizeConfig.heightMultiplier * 19,
          width: SizeConfig.widthMultiplier * 37,

          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
              border: Border.all(
                  width: 1,
                  color: Hexcolor(
                      '#CCCCCC') //                   <--- border width here
                  ),
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsetsDirectional.only(
                    top: SizeConfig.heightMultiplier * 0.5),
                child: Image.asset(
                  url,
                  height: SizeConfig.heightMultiplier * 10,
                  fit: BoxFit.cover,
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Text(
                dec,
                style: TextStyle(fontSize: SizeConfig.textMultiplier * 2),
              )
            ],
          ),
        ),
      ),
    );
  }

  bool hideSilentMethods() {
    return verificationMethod == 4 || verificationMethod == 3 ? true : false;
  }

/*
 *@author: Elham Rababah
 *@Date:15/4/2020
 *@param: oTPSendType
 *@return:
 *@desc:   send Activation Code By Otp Notification Type
 */
  sendActivationCodeByOtpNotificationType(oTPSendType, AuthProvider authProv) {
    // TODO : build enum for verfication method
    if (oTPSendType == 1 || oTPSendType == 2) {
      widget.changeLoadingStata(true);

      Map<String, dynamic> model = {
        "LogInTokenID": _loggedUser['LogInTokenID'],
        "Channel": 9,
        "MobileNumber": _loggedUser['MobileNumber'],
        "IPAdress": "11.11.11.11",
        "LanguageID": 2,
        "ProjectID": 15, //TODO : this should become daynamci
        "ZipCode": _loggedUser['ZipCode'],
        "UserName": _loggedUser['List_MemberInformation'][0]['MemberID'],
        "OTP_SendType": oTPSendType
      };
      authProv.sendActivationCodeByOtpNotificationType(model).then((res) {
        widget.changeLoadingStata(false);

        if (res['MessageStatus'] == 1) {
          Navigator.of(context).pushReplacementNamed(VERIFY_ACCOUNT,
              arguments: {'model': model});
        } else {
          print(res['ErrorEndUserMessage']);
          helpers.showErrorToast(res['ErrorEndUserMessage']);
        }
      }).catchError((err) {
        print('$err');
        widget.changeLoadingStata(false);

        helpers.showErrorToast();
      });
    } else {
      // TODO route to this page with parameters to inicate we should present 2 option
      if (Platform.isAndroid && oTPSendType == 3) {
        helpers.showErrorToast('Your device not support this feature');
      } else {
        Navigator.of(context).pushNamed(VERIFICATION_METHODS,
            arguments: {'verificationMethod': oTPSendType});
      }
    }
  }
}
