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

import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.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/style.dart';

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

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

class _CreatePassPageState extends State<CreatePassPage> {
  final String backImg = camobkimg;
  //final TextEditingController txtOtp = TextEditingController();
  String newpass = "";
  String confirmpass = "";

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

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

  handleBackTo() {
    Navigator.of(context).pop();
  }

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

  signIn() async {
    setState(() {
      isVerifying = true;
    });
    String username = appData.dbUser['username'];

    if (newpass != confirmpass) {
      setState(() {
        isVerifying = false;
      });
      showAlert(
          context, AlertDialogType.ERROR, "Error", "Passkeys do not match");
      return;
    } else {
      if (newpass == "") {
        setState(() {
          isVerifying = false;
        });
        showAlert(context, AlertDialogType.ERROR, "Error",
            "Passkeys can not be empty");
        return;
      }
    }

    Encrypted passkey = encryptIt(username, newpass);

    appData.dbUser["passkey"] = passkey.base64;

    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {
        "passkey": passkey.base64,
        "token": appData.dbUser['token']
      };
      var response = await dio.post(
        "updatepasskey",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      print(response.data);
      print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          appData.passKey = newpass;
          showAlert(
              context, AlertDialogType.SUCCESS, "Success", "Messages Secured");
          if (widget.isFirst) {
            Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(builder: (context) => HomePage()),
                (Route<dynamic> route) => false);
          } else {
            Navigator.of(context).pop();
          }
        } else {
          showAlert(
              context, AlertDialogType.ERROR, "Error", data["data"]["message"]);
        }
      }
    } catch (e) {
      showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
    }
    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(
                  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: Colors.white.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),
                          const Text(
                            "Nigerian Army Instant Messenger",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: armyGreen,
                                fontSize: 24.0,
                                fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 20.0),
                          const Text(
                              "Please Create New Pass key to Secure Messages.",
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: 18.0)),
                          const SizedBox(height: 20.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,
                                style: TextStyle(fontSize: 17),
                                onChanged: (pin) {
                                  //print("Changed: " + pin);
                                },
                                onCompleted: (pin) {
                                  setState(() {
                                    newpass = pin;
                                  });
                                  print("Completed: " + pin);
                                }),
                          ),
                          const SizedBox(height: 30.0),
                          const Text("Confirm Pass Key.",
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: 18.0)),
                          const SizedBox(height: 20.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,
                                style: TextStyle(fontSize: 17),
                                onChanged: (pin) {
                                  //print("Changed: " + pin);
                                },
                                onCompleted: (pin) {
                                  setState(() {
                                    confirmpass = pin;
                                  });
                                  print("Completed: " + pin);
                                }),
                          ),
                          const SizedBox(height: 30.0),
                          SizedBox(
                            width: double.infinity,
                            child: getElevatedButton(armyGreen,
                                isVerifying ? "Please Wait..." : "CREATE KEY",
                                () {
                              if (!isVerifying) {
                                signIn();
                              }
                            }),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
