import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:naim/classes/appdata.dart';
import 'dart:ui';
import 'package:naim/classes/assets.dart';
import 'package:naim/classes/cipher.dart';
import 'package:naim/widgets/input.dart';
import 'package:otp_text_field/otp_field.dart';
import 'package:otp_text_field/otp_text_field.dart';
import 'package:otp_text_field/style.dart';

import '../../classes/Auth.dart';
import '../../classes/Authenticate.dart';
import '../home.dart';

class UnlockPage extends StatefulWidget {
  @override
  UnlockPage(this.isFirst);
  _UnlockPageState createState() => _UnlockPageState();
  bool isFirst;
}

class _UnlockPageState extends State<UnlockPage> {
  final String backImg = camobkimg;
  //final TextEditingController txtOtp = TextEditingController();
  String txtOtp = "";

  bool isVerifying = false;
  String msg = "Please wait...";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void setState(fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  signIn() async {
    if (txtOtp.isEmpty) {
      showAlert(
          context, AlertDialogType.ERROR, "Error", "Please enter a passkey");
    }
    setState(() {
      isVerifying = true;
    });

    String username = appData.dbUser['username'];
    String passkey = appData.dbUser['passkey'];
    print('username:==$username====');
    print('passkey: $passkey');
    try {
      String decrypt = decryptIt(passkey, txtOtp);
      print("=====================|$decrypt|===================");
      if (decrypt == username) {
        appData.passKey = txtOtp;
        setState(() {
          isVerifying = false;
        });
        if (widget.isFirst) {
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => HomePage()),
              (Route<dynamic> route) => false);
        } else {
          Navigator.of(context).pop();
        }
        return;
      } else {
        setState(() {
          isVerifying = false;
        });
        showAlert(context, AlertDialogType.ERROR, "Sorry",
            "Incorrect Pass key, please try again");
        return;
      }
    } catch (e) {
      print(e);
      showAlert(context, AlertDialogType.ERROR, "Sorry",
          "Incorrect Pass key, please try again");
    }
    setState(() {
      isVerifying = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: Scaffold(
        body: Container(
          height: double.infinity,
          decoration: BoxDecoration(
              image: DecorationImage(
                  colorFilter: ColorFilter.mode(
                      appColors.backgroundColor(context), BlendMode.multiply),
                  image: AssetImage(backImg),
                  fit: BoxFit.cover)),
          child: Stack(
            children: <Widget>[
              Center(
                child: SingleChildScrollView(
                  child: Container(
                    margin: const EdgeInsets.all(28.0),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 24.0, vertical: 48.0),
                    decoration: BoxDecoration(
                      color:
                          appColors.backgroundColor(context).withOpacity(0.8),
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    child: BackdropFilter(
                      filter: ImageFilter.blur(
                        sigmaX: 1.0,
                        sigmaY: 1.0,
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          Container(
                              width: 100,
                              height: 100,
                              child: Image.asset(appLogo)),
                          const SizedBox(height: 10.0),
                          Text(
                            "Nigerian Army Instant Messenger",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: appColors.armyColor(context),
                                fontSize: 24.0,
                                fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 20.0),
                          Text(
                              "Your Messages Are Encrypted, Use Your Pass Key To Unlock It.",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 18.0,
                                  color: appColors.textColor(context))),
                          const SizedBox(height: 30.0),
                          SizedBox(
                            width: double.infinity,
                            child: OTPTextField(
                                obscureText: true,
                                length: 6,
                                width: MediaQuery.of(context).size.width -
                                    (48 + 52),
                                textFieldAlignment:
                                    MainAxisAlignment.spaceAround,
                                fieldWidth: (MediaQuery.of(context).size.width /
                                        6) -
                                    (MediaQuery.of(context).size.width * 0.06),
                                fieldStyle: FieldStyle.box,
                                outlineBorderRadius: 15,
                                otpFieldStyle: OtpFieldStyle(
                                    borderColor:
                                        appColors.textColorSecondary(context),
                                    enabledBorderColor:
                                        appColors.textColorSecondary(context),
                                    focusBorderColor:
                                        appColors.armyColor(context)),
                                style: TextStyle(
                                    fontSize: 17,
                                    color: appColors.textColor(context)),
                                onChanged: (pin) {
                                  //print("Changed: " + pin);
                                },
                                onCompleted: (pin) {
                                  setState(() {
                                    txtOtp = pin;
                                  });
                                  print("Completed: " + pin);
                                }),
                          ),
                          const SizedBox(height: 30.0),
                          SizedBox(
                            width: double.infinity,
                            child: getElevatedButton(
                                appColors.armyColor(context),
                                isVerifying ? "Please Wait..." : "UNLOCK", () {
                              if (!isVerifying) {
                                signIn();
                              }
                            }),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
