import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:local_auth/error_codes.dart' as auth_error;
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.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 '../../widgets/shared/dr_app_circular_progress_Indeicator.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

class KnownUserLogin extends StatefulWidget {
  @override
  _KnownUserLoginState createState() => _KnownUserLoginState();
}

class _KnownUserLoginState extends State<KnownUserLogin> {
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  final LocalAuthentication auth = LocalAuthentication();

  String _authorized = "not Authorized";
  bool _isAuthenticating = false;
  Future _loggedUserFuture;
  var _loggedUser;
  int _loginType = 1;
  String _platformImei;
  Future _loginTypeFuture;

  Map _loginTypeMap = {
    1: {
      "name": "SMS",
      'imageUrl': 'assets/images/verification_sms_lg_icon.png',
    },
    2: {
      "name": "FingerPrint",
      'imageUrl': 'assets/images/verification_fingerprint_lg_icon.png'
    },
    3: {
      "name": "Face",
      'imageUrl': 'assets/images/verification_faceid_lg_icon.png'
    },
    4: {
      "name": "WhatsApp",
      'imageUrl': 'assets/images/verification_whatsapp_lg_icon.png'
    }
  };

  Future<void> getSharedPref() async {
    sharedPref.getObj(LOGGED_IN_USER).then((userInfo) {
      _loggedUser = userInfo;
    });
    sharedPref.getString('platformImei').then((imei) {
      _platformImei = imei;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    AuthViewModel authProv = Provider.of<AuthViewModel>(context);
    // var imeiModel = {'IMEI': _platformImei};
    // _loginTypeFuture = authProv.selectDeviceImei(imeiModel);
    return FutureBuilder(
        future: Future.wait([_loggedUserFuture, _loginTypeFuture]),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          _loginTypeFuture.then((res) {
            _loginType =
                2; //res['SELECTDeviceIMEIbyIMEI_List'][0]['LogInType'];
          }).catchError((err) {
            print('${err}');
            DrAppToastMsg.showErrorToast(err);
          });
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return DrAppCircularProgressIndeicator();
            default:
              if (snapshot.hasError) {
                DrAppToastMsg.showErrorToast('Error: ${snapshot.error}');
                return Text('Error: ${snapshot.error}');
              } else {
                return Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Stack(children: [
                      Container(
                        decoration: BoxDecoration(
                            border: Border.all(
                              color: HexColor('#CCCCCC'),
                            ),
                            borderRadius: BorderRadius.circular(50)),
                        margin: const EdgeInsets.fromLTRB(0, 20.0, 30, 0),
                        child: Row(
                          // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                                height: 100,
                                width: 100,
                                decoration: new BoxDecoration(
                                    // color: Colors.green, // border color
                                    shape: BoxShape.circle,
                                    border:
                                        Border.all(color: HexColor('#CCCCCC'))),
                                child: CircleAvatar(
                                  child: Image.asset(
                                    'assets/images/dr_avatar.png',
                                    fit: BoxFit.cover,
                                  ),
                                )),
                            Container(
                              margin: EdgeInsets.symmetric(
                                  vertical: 3, horizontal: 15),
                              child: Column(
                                //  mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    _loggedUser['List_MemberInformation'][0]
                                        ['MemberName'],
                                    style: TextStyle(
                                        color: HexColor('515A5D'),
                                        fontSize:
                                            2.5 * SizeConfig.textMultiplier,
                                        fontWeight: FontWeight.w800),
                                  ),
                                  Text(
                                    'ENT Spec',
                                    style: TextStyle(
                                        color: HexColor('515A5D'),
                                        fontSize:
                                            1.5 * SizeConfig.textMultiplier),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      Positioned(
                          top: 7,
                          right: 70,
                          child: Image.asset(
                            'assets/images/close_icon.png',
                            fit: BoxFit.cover,
                          ))
                    ]),
                    buildVerificationTypeImageContainer(),
                    buildButtonsContainer(context)
                  ],
                );
              }
          }
        });
  }

  Container buildVerificationTypeImageContainer() {
    print('${_loginTypeMap[_loginType]}');
    return Container(
        height: 200,
        width: 200,
        child: Center(
          child: Image.asset(
            _loginTypeMap[_loginType]['imageUrl'],
            fit: BoxFit.cover,
          ),
        ));
  }

  //
  Container buildButtonsContainer(BuildContext context) {
    return Container(
      margin: EdgeInsetsDirectional.fromSTEB(0, 0, 30, 0),
      width: double.infinity,
      child: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: _authenticate,
            elevation: 0.0,
            child: Container(
              width: double.infinity,
              height: 50,
              child: Center(
                child: Text(
                  "Verify using ${_loginTypeMap[_loginType]['name']}"
                      .toUpperCase(),
                  // textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 2.5 * SizeConfig.textMultiplier),
                ),
              ),
            ),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: BorderSide(width: 0.5, color: HexColor('#CCCCCC'))),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
            width: double.infinity,
            height: 50,
            child: FlatButton(
                onPressed: () {
                  navigateToMoreOption();
                },
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(
                        width: 1, color: Theme.of(context).primaryColor)),
                child: Text(
                  "More verification Options".toUpperCase(),
                  style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 2.5 * SizeConfig.textMultiplier),
                )),
          ),
          SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }

  navigateToMoreOption() {
    Navigator.of(context).pushNamed(VERIFICATION_METHODS);
  }

  _authenticate() {
    if (_loginType == 1) {
      _authenticateBySMS();
    }
    if (_loginType == 2) {
      _authenticateByFingerPrint();
    }
    if (_loginType == 3) {
      _authenticateByFace();
    }
    if (_loginType == 4) {
      _authenticateByWhatsApp();
    }
  }

  Future<void> _authenticateByFingerPrint() async {
    _getAvailableBiometrics();
    bool authenticated = false;
    try {
      setState(() {
        _isAuthenticating = true;
        _authorized = 'Authenticating';
      });
      authenticated = await auth.authenticateWithBiometrics(
          localizedReason: 'Scan your fingerprint to authenticate',
          useErrorDialogs: true,
          stickyAuth: false);
      setState(() {
        _isAuthenticating = false;
        _authorized = 'Authenticating';
      });
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    final String message = authenticated ? 'Authorized' : 'Not Authorized';
    if (message == 'Authorized') {
      navigateToHome();
    }
    setState(() {
      print('_authorized' + _authorized);
      _authorized = message;
      print('_authorized' + _authorized);
    });
  }

  Future<void> _authenticateBySMS() {
    print('_authenticateBySMS');
  }

  Future<void> _authenticateByFace() {
    print('_authenticateByFace');
  }

  Future<void> _authenticateByWhatsApp() {
    print('_authenticateByWhatsApp');
  }

  Future<void> _getAvailableBiometrics() async {
    List<BiometricType> availableBiometrics;
    try {
      availableBiometrics = await auth.getAvailableBiometrics();
    } on PlatformException catch (e) {
      print(e);
      if (e.code == auth_error.notAvailable) {
        showErorrMsg("Auth Methods Not Available");
      } else if (e.code == auth_error.passcodeNotSet) {
        showErorrMsg("Auth Methods Not passcodeNotSet");
      } else if (e.code == auth_error.permanentlyLockedOut) {
        showErorrMsg("Auth Methods Not permanentlyLockedOut");
      }
    }
    if (!mounted) return;

    setState(() {
      print('availableBiometrics $availableBiometrics');
    });
  }

  navigateToHome() {
    Navigator.of(context).pushNamed(HOME);
  }

  showErorrMsg(localMsg) {
    DrAppToastMsg.showErrorToast(localMsg);
  }
}
