import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:hmg_flutter_template/classes/colors.dart';
import 'package:hmg_flutter_template/classes/date-utils.dart';
import 'package:hmg_flutter_template/classes/enums.dart';
import 'package:hmg_flutter_template/config/routes.dart';
import 'package:hmg_flutter_template/extensions/int_extensions.dart';
import 'package:hmg_flutter_template/extensions/string_extensions.dart';
import 'package:hmg_flutter_template/extensions/util_extensions.dart';
import 'package:hmg_flutter_template/extensions/widget_extensions.dart';
import 'package:hmg_flutter_template/generated/locale_keys.g.dart';
import 'package:hmg_flutter_template/main.dart';
import 'package:hmg_flutter_template/provider/login_provider_model.dart';
import 'package:hmg_flutter_template/ui/login/widgets/verification_method_card.dart';
import 'package:hmg_flutter_template/widgets/button/default_button.dart';
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';
import 'package:sizer/sizer.dart';

// WhatsApp 2
// SMS 1
// Face ID 3
// Finger Print 4

class LoginMethodsPage extends StatefulWidget {
  const LoginMethodsPage({Key? key}) : super(key: key);

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

class LoginMethodsPageState extends State<LoginMethodsPage> {
  bool isMoreOption = false;
  bool onlySMSBox = false;

  LoginType? loginType;
  AuthMethodTypes? selectedAuthType;
  late LoginProviderModel loginProviderModel;

  @override
  Widget build(BuildContext context) {
    loginType ??= ModalRoute.of(context)!.settings.arguments as LoginType;

    loginProviderModel = context.read<LoginProviderModel>();
    return Scaffold(
      // appBar: AppBar(
      //   backgroundColor: Colors.transparent,
      //   leading: null,
      //   // actions: [Center(child: "Employee Digital ID".toText12(color: MyColors.textMixColor, isUnderLine: true).onPress(() {})), 21.width],
      // ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: const EdgeInsets.all(21),
        child: Column(
          children: [
            Expanded(
              child: SafeArea(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      21.height,
                      if (loginType == LoginType.SILENT_LOGIN && appState.lastLoginImeiDate != null)
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            LocaleKeys.welcomeBack.tr().toText12(),
                            ("${appState.lastLoginImeiDate!.titleDescription!} ${appState.lastLoginImeiDate!.doctorName!}").toText20(isBold: true),
                            heightSpacer3per(),
                            LocaleKeys.wouldYouLikeToLoginWithCurrentUsername.tr().toText14(),
                            heightSpacer3per(),
                            Container(
                              padding: const EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: const BorderRadius.all(Radius.circular(10)),
                                border: Border.all(color: HexColor('#707070'), width: 0.1),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      LocaleKeys.lastLoginDetails.tr().toText13(),
                                      SizedBox(
                                        width: 55.w,
                                        child: Row(
                                          children: [
                                            "${LocaleKeys.verificationType.tr()} : ".toText11(),
                                            loginProviderModel.getType(appState.lastLoginImeiDate!.logInTypeID ?? 1).toText11(isBold: true),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      (appState.lastLoginImeiDate!.editedOn != null
                                              ? AppDateUtils.getDayMonthYearDateFormatted(AppDateUtils.convertStringToDate(appState.lastLoginImeiDate!.editedOn ?? ""), isMonthShort: true)
                                              : appState.lastLoginImeiDate!.createdOn != null
                                                  ? AppDateUtils.getDayMonthYearDateFormatted(AppDateUtils.convertStringToDate(appState.lastLoginImeiDate!.createdOn ?? ""), isMonthShort: true)
                                                  : '--')
                                          .toText11(isBold: true),
                                      heightSpacer06per(),
                                      (appState.lastLoginImeiDate!.editedOn != null
                                              ? AppDateUtils.getHour(AppDateUtils.convertStringToDate(appState.lastLoginImeiDate!.editedOn ?? ""))
                                              : appState.lastLoginImeiDate!.createdOn != null
                                                  ? AppDateUtils.getHour(AppDateUtils.convertStringToDate(appState.lastLoginImeiDate!.createdOn ?? ""))
                                                  : '--')
                                          .toText10()
                                    ],
                                  )
                                ],
                              ),
                            ),
                            heightSpacer3per(),
                            LocaleKeys.pleaseVerify.tr().toText14().paddingOnly(left: 1.w),
                            heightSpacer2per(),
                          ],
                        ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          if (loginType == LoginType.FROM_LOGIN || loginType == LoginType.SILENT_WITH_OTP)
                            Column(
                              children: [
                                LocaleKeys.pleaseVerifyForBio.tr().toText14(),
                                21.height,
                              ],
                            ),
                          if (loginType == LoginType.FROM_LOGIN || loginType == LoginType.SILENT_LOGIN)
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Expanded(
                                  child: VerificationMethodsList(
                                    authMethodType: AuthMethodTypes.faceID,
                                    isBioAvailable: loginProviderModel.isFaceBioAvailable,
                                    authenticateUser: (AuthMethodTypes authMethodType, isActive) async {
                                      bool isAuthenticated = await loginProviderModel.loginWithFaceIDAndBiometrics();
                                      if (isAuthenticated) {
                                        appState.lastLoginTyp = loginProviderModel.getLoginMethodId(authMethodType);
                                        if (loginType == LoginType.FROM_LOGIN) {
                                          setState(() {
                                            loginType = LoginType.FROM_LOGIN;
                                          });
                                        } else if (loginType == LoginType.SILENT_LOGIN) {
                                          if (appState.lastLoginImeiDate!.logInTypeID == loginProviderModel.getLoginMethodId(authMethodType)) {
                                            loginProviderModel.sendActivationCode(
                                              appState.memberBeforeLogin!,
                                              appState.projectID,
                                              loginProviderModel.getLoginMethodId(AuthMethodTypes.sms),
                                              loginType ?? LoginType.FROM_LOGIN,
                                              isNeedBinding: false,
                                            );
                                          } else {
                                            setState(() {
                                              loginType = LoginType.SILENT_WITH_OTP;
                                            });
                                          }
                                        }
                                      } else {
                                        print("Authentication Failed");
                                      }
                                    },
                                  ),
                                ),
                                21.width,
                                Expanded(
                                  child: VerificationMethodsList(
                                    authMethodType: AuthMethodTypes.fingerPrint,
                                    isBioAvailable: loginProviderModel.isFingerBioAvailable,
                                    authenticateUser: (AuthMethodTypes authMethodType, isActive) async {
                                      bool isAuthenticated = await loginProviderModel.loginWithFaceIDAndBiometrics();
                                      if (isAuthenticated) {
                                        appState.lastLoginTyp = loginProviderModel.getLoginMethodId(authMethodType);
                                        if (loginType == LoginType.FROM_LOGIN) {
                                          setState(() {
                                            loginType = LoginType.FROM_LOGIN;
                                          });
                                        } else if (loginType == LoginType.SILENT_LOGIN) {
                                          if (appState.lastLoginImeiDate!.logInTypeID == loginProviderModel.getLoginMethodId(authMethodType)) {
                                            loginProviderModel.sendActivationCode(
                                              appState.memberBeforeLogin!,
                                              appState.projectID,
                                              loginProviderModel.getLoginMethodId(AuthMethodTypes.sms),
                                              loginType ?? LoginType.FROM_LOGIN,
                                              isNeedBinding: false,
                                            );
                                          } else {
                                            setState(() {
                                              loginType = LoginType.SILENT_WITH_OTP;
                                            });
                                          }
                                        }
                                      } else {
                                        print("Authentication Failed");
                                      }
                                    },
                                  ),
                                ),
                              ],
                            ),
                          21.height,
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Expanded(
                                child: VerificationMethodsList(
                                  authMethodType: AuthMethodTypes.sms,
                                  authenticateUser: (AuthMethodTypes authMethodType, isActive) {
                                    if (loginType == LoginType.FROM_LOGIN || loginType == LoginType.SILENT_LOGIN) {
                                      if (appState.lastLoginTyp == -1) appState.lastLoginTyp = loginProviderModel.getLoginMethodId(authMethodType);
                                      if (loginType == LoginType.SILENT_LOGIN) {
                                        loginType = LoginType.SILENT_WITH_OTP;
                                      }
                                    }
                                    loginProviderModel.sendActivationCode(
                                      appState.memberBeforeLogin!,
                                      appState.projectID,
                                      loginProviderModel.getLoginMethodId(AuthMethodTypes.sms),
                                      loginType ?? LoginType.FROM_LOGIN,
                                    );
                                  },
                                ),
                              ),
                              21.width,
                              Expanded(
                                child: VerificationMethodsList(
                                  authMethodType: AuthMethodTypes.whatsApp,
                                  authenticateUser: (AuthMethodTypes authMethodType, isActive) {
                                    if (loginType == LoginType.FROM_LOGIN || loginType == LoginType.SILENT_LOGIN) {
                                      if (appState.lastLoginTyp == -1) appState.lastLoginTyp = loginProviderModel.getLoginMethodId(authMethodType);
                                      if (loginType == LoginType.SILENT_LOGIN) {
                                        loginType = LoginType.SILENT_WITH_OTP;
                                      }
                                    }
                                    loginProviderModel.sendActivationCode(
                                      appState.memberBeforeLogin!,
                                      appState.projectID,
                                      loginProviderModel.getLoginMethodId(AuthMethodTypes.whatsApp),
                                      loginType ?? LoginType.FROM_LOGIN,
                                    );
                                  },
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      12.height,
                    ],
                  ),
                ),
              ),
            ),
            21.height,
            DefaultButton(
              LocaleKeys.useAnotherAccount.tr(),
              () async {
                Navigator.pushReplacementNamed(context, AppRoutes.login, arguments:false);
              },
              colors: const [
                MyColors.redColor,
                MyColors.redColor,
              ],
            ),
          ],
        ),
      ),
    );
  }
}
