import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:mhunt_launcher/Backend/Backend.dart';
import 'package:mhunt_launcher/Widgets/CustomWidgets.dart';
import 'package:mhunt_launcher/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isReg = false;

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

    kickstartAnimations();

    //autoLogin();
  }

  void autoLogin() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.containsKey("username") && prefs.containsKey("password")) {
      usernameController.text = prefs.getString("username") ?? '';
      passwordController.text = prefs.getString("password") ?? '';

      LoginOrReg();
    }
  }

  void kickstartAnimations() async {
    await Future.delayed(const Duration(milliseconds: 500));

    setState(() {
      op1 = 1;
      op2 = 1;
      op3 = 1;
    });
  }

  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    const Color backgroundColor = Color(0xFF111111);
    const Color modalColor = Color(0xFFFFFFFF);

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: CustomBody(
          context: context,
          onAnimEnd: () {
            // kickstartAnimations();
            setState(() {});
          },
          child: Center(
            child: web3LoginCard()
          ))
    );
  }

  Widget web3LoginCardContent0(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const Text(
          "Welcome to W3B Launcher",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 50,),
        GlassButton(onTap: loginWeb3, child: Text("Loing / Signup"), width: 250,height: 50)
      ],
    );
  }

  Widget web3LoginCardContent1(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.all(18.0),
          child: const Text(
            "Complete logging in on your browser",
            style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
          ),
        )
      ],
    );
  }
  TextEditingController usernameEditingController= TextEditingController();
  Widget web3LoginCardNewUsername(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const Text(
          "Enter a username",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 50,),
        SizedBox(width: 250,child: TextField(controller: usernameEditingController,textAlign: TextAlign.center,)),
        SizedBox(width: 250,child:usernameExists ? Text("Username is taken",style: TextStyle(color: Colors.red),) : Container()),
        SizedBox(height: 20,),

        !web3loginworking ? GlassButton(onTap: completeweb3, child: Text("Complete"), width: 250,height: 50) : GlassButton(onTap: (){}, child: Text("Loading"), width: 250,height: 50)
      ],
    );
  }

  Widget web3LoginCardContent(){
    switch(web3loginState){
      case 1:
        return web3LoginCardContent1();
        break;

      case 2:
        return web3LoginCardNewUsername();
        break;

      default:
        return web3LoginCardContent0();
        break;
    }
  }

  Widget web3LoginCard(){
    return GlassCard(child: Padding(padding: EdgeInsets.all(20),child:
      web3LoginCardContent()
    )
    );
  }
  int web3loginState = 0;
  String web3id = "";
  void loginWeb3() async{
    String requestId = await Backend.CreateRequest();
    setState(() {
      web3loginState = 1;
    });
    launchUrl(Uri.parse('https://auth.playpoolstudios.com/?request_id=${requestId}'));
    String requestResponse = "-1";
    while(requestResponse == "-1"){
      await Future.delayed(const Duration(seconds: 1));
      requestResponse = await Backend.GetRequestResponse(requestId);
    }

    web3id = requestResponse;
    String dispName = await Backend.GetDisplayName(web3id);
    if(dispName == "-1"){
      setState(() {
        web3loginState = 2;
      });
    }else{
      usernameEditingController.text = dispName;
      completeweb3();
    }

    // await Backend.Login(requestResponse, requestResponse);
    // OnLoginSuccess();
  }

  bool usernameExists = false;
  bool web3loginworking = false;
  void completeweb3() async{
    if(web3id.length < 3){
      setState(() {
        web3loginState=0;
      });
      return;
    }

    if(usernameEditingController.text.isEmpty){return;}
    setState((){ web3loginworking=true; });
    bool usernameValidated = await Backend.GetUsernameValidation(usernameEditingController.text);
    if(!usernameValidated){
      setState(() {
        usernameExists = true;
      });
      setState((){ web3loginworking=false; });

      return;
    }

    await Backend.Register(web3id,web3id,usernameEditingController.text);
    await Backend.Login(usernameEditingController.text, web3id);

    OnLoginSuccess();
  }


  Widget TraditionalLoginCard(){
    return GlassCard(
        child: Container(
          padding: EdgeInsets.all(25),
          width: 600,
          height: 400,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                "Welcome to W3B Launcher",
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                       Text("Username "),
                       SizedBox(
                          width: 300,
                          child: TextField(
                            controller: usernameController,
                          ))
                    ],
                    mainAxisAlignment: MainAxisAlignment.center,
                  ),
                  Row(children: [
                    Text("Password "),
                    SizedBox(
                        width: 300,
                        child: TextField(
                          controller: passwordController,
                        ))
                  ], mainAxisAlignment: MainAxisAlignment.center),
                  SizedBox(
                    height: 30,
                  ),
                  GlassButton(onTap: LoginOrReg, child: Text(isReg ? "Register" : "Login"), width: 150, height: 40),
                ],
              ),
              Row(children: [
                Text(isReg ? "Already have an Account? " : "Don't have an Account? "),
                InkWell(
                  child: Text(
                    isReg ? "Login Here" : "Register Here",
                    style: TextStyle(color: Colors.blue),
                  ),
                  onTap: () {
                    setState(() {
                      isReg = !isReg;
                    });
                  },
                )
              ], mainAxisAlignment: MainAxisAlignment.center)
            ],
          ),
        ));
  }

  void LoginOrReg() async {
    // if(kDebugMode){
    //   Navigator.of(context).push(MaterialPageRoute(builder: (context)=>HomePage()));
    //   return;
    // }
    bool success = false;
    if (isReg) {
      success = await Backend.Register(usernameController.text, passwordController.text, usernameController.text);
    } else {
      success = await Backend.Login(usernameController.text, passwordController.text);
    }

    if (success) {
      OnLoginSuccess();
    }
  }

  void OnLoginSuccess() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('username', usernameController.text);
    prefs.setString('password', passwordController.text);

    Navigator.of(context).push(MaterialPageRoute(builder: (context) => HomePage()));
  }
}
