import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/providers/auth_provider.dart';
import 'package:initial_folder/providers/login_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/screens/home/home_screen.dart';
import 'package:initial_folder/screens/login/components/get_user_data.dart';
import 'package:initial_folder/screens/login/login_with_google/login_google_screen.dart';
import 'package:initial_folder/screens/registrasi/registrasi_with_email/registrasi_email_screen.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/custom_text_form_field.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/login_regist/default_icon_button.dart';
import 'package:initial_folder/widgets/login_regist/failed_login.dart';
import 'package:initial_folder/widgets/login_regist/footer.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import '../reset/reset_screen.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';

class LoginEmail extends StatefulWidget {
  final _LoginEmailState loginEmailState = _LoginEmailState();

  static String routeName = "/login_email";
  LoginEmail({Key? key}) : super(key: key);

  @override
  _LoginEmailState createState() => loginEmailState;
}

class _LoginEmailState extends State<LoginEmail> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final TextEditingController emailController = TextEditingController(text: '');

  final TextEditingController passwordController =
      TextEditingController(text: '');
  bool isLoading = false;
  bool failed = false;
  bool _isObscure = true;
  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var loginProvider = Provider.of<LoginProvider>(context, listen: false);
    SizeConfig().init(context);
    AuthProvider authProvider = Provider.of<AuthProvider>(context);
     final themeProvider = Provider.of<ThemeProvider>(context,listen: false);

    handleSignIn() async {
      setState(() {
        isLoading = true;
      });

      if (await authProvider.login(
        email: emailController.text,
        password: passwordController.text,
      )) {
        Condition.loginEmail = true;
        await UsersInfo().setEmail(emailController.text);

        await getUserData(context);

        Navigator.of(context).pushNamedAndRemoveUntil(
            HomeScreen.routeName, (Route<dynamic> route) => false);
      } else {
        setState(() {
          failed = true;
        });
      }

      setState(() {
        isLoading = false;
      });
    }

    void _validateInputs() {
      if (this._formKey.currentState!.validate()) {
        handleSignIn();
      }
    }

    Widget form() {
      Widget emailInput() {
        String? kondisiikonemail;
        String? emailValidation = validateEmail(emailController.text);
        if (emailController.text.isEmpty) {
          kondisiikonemail = 'abu2';
        } else {
          if (emailValidation == 'Email tidak boleh kosong' ||
              emailValidation == 'Mohon masukkan email yang valid') {
            kondisiikonemail = 'merah';
          } else {
            kondisiikonemail = 'ijo';
          }
        }
        emailController.addListener(() {
          if (emailController.text.isEmpty) {
            kondisiikonemail = 'abu2';
          } else {
            if (emailValidation == 'Email tidak boleh kosong' ||
                emailValidation == 'Mohon masukkan email yang valid') {
              kondisiikonemail = 'merah';
            } else {
              kondisiikonemail = 'ijo';
            }
          }
          setState(() {});
        });
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: emailController,
          hinttext: 'Inputyouremail@gmail.com',
          title: 'Email',
          validate: validateEmail,
          textInputAction: TextInputAction.next,
          suffix: Icon(
            FeatherIcons.checkCircle,
            color: kondisiikonemail == 'ijo'
                ? Colors.green
                : kondisiikonemail == 'merah'
                    ? Colors.red
                    : Colors.grey,
            size: 18,
          ),
        );
      }

      Widget passwordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: passwordController,
          hinttext: 'Input your password',
          title: 'Password',
          obscuretext: _isObscure,
          validate: validatePassword,
          suffix: GestureDetector(
            onTap: () => setState(() {
              _isObscure = !_isObscure;
            }),
            child: _isObscure
                ? Icon(
                    FeatherIcons.eyeOff,
                    color: secondaryColor,
                    size: 18,
                  )
                : Icon(
                    FeatherIcons.eye,
                    color: secondaryColor,
                    size: 18,
                  ),
          ),
          textInputAction: TextInputAction.done,
        );
      }

      Widget forgotPassword() {
        MediaQuery.of(context).platformBrightness;

        return Container(
            child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(right: getProportionateScreenWidth(12)),
              alignment: AlignmentDirectional.topEnd,
              child: GestureDetector(
                child: Text(
                  'Lupa password?',
                  style: thirdTextStyle.copyWith(
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(14),
                  ),
                ),
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => ResetScreen(
                        email: emailController.text,
                      ),
                    ),
                  );
                },
              ),
            ),
            SizedBox(height: getProportionateScreenHeight(35)),
          ],
        ));
      }

      Widget button() {
        return Padding(
          padding:
              EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(60)),
          child: isLoading
              ? LoadingButton(
                  backgroundButtonColor: primaryColor,
                  textButtonColor: Color(0xff050505))
              : DefaultButton(
                  text: 'Log In',
                  press: _validateInputs,
                ),
        );
      }

      return Form(
        key: _formKey,
        child: Column(
          children: [emailInput(), passwordInput(), forgotPassword(), button()],
        ),
      );
    }

    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.all(getProportionateScreenWidth(25)),
                child: Align(
                    alignment: Alignment.center,
                    child: Text('Log In',
                        style: thirdTextStyle.copyWith(
                            fontWeight: FontWeight.w900,
                            fontSize: getProportionateScreenWidth(20),
                            letterSpacing: 0.5))),
              ),
              Container(
                child: Align(
                    alignment: Alignment.center,
                    child: failed
                        ? FailedLogin(
                            style: primaryTextStyle.copyWith(
                              color: sevenColor,
                            ),
                            text:
                                'Terdapat kendala dalam login, periksa kembali email dan password anda',
                          )
                        : SizedBox()),
              ),
              SizedBox(
                height: getProportionateScreenHeight(32),
              ),
              form(),
              SizedBox(height: getProportionateScreenHeight(10)),
              Footer(
                textOne: 'Belum punya akun? ',
                textTwo: 'Register',
                route: RegistrationEmail.routeName,
              ),
              Consumer<LoginProvider>(
                builder: (context, value, child) {
                  return Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: getProportionateScreenWidth(30.0)),
                    child: value.loadGoogle
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                width: 17,
                                height: 17,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation(
                                    themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                                  ),
                                ),
                              ),
                              SizedBox(
                                width: getProportionateScreenWidth(6),
                              ),
                              Text(
                                'Loading',
                                style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(14),
                                    fontWeight: semiBold,
                                    color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode ,
                                    letterSpacing: 0.3),
                              ),
                            ],
                          )
                        :
                        // fitur login googgle ini bisa bekerja hanya ketika sha 1 dan sha 256 laptop mu sudah di daftarkan-
                        // di firebase vocasia, caranya buka terminal vscode, masuk ke folder android dengan-
                        // cara cd android, setelah itu jalankan ./gradlew signingReport nanti muncul di situ sha nya-
                        // setelah muncul, berikan sha key nya ke bang sergi atau bang rizky untuk di daftarkan-
                        // di fingerprint firebase vocasia
                        DefaultIconButton(
                            text: "Continue With Google",
                            press: () async {
                              loginProvider.loadGoogleActive(true);
                              // baca comment di atas
                              await LoginGoogle().handleLoginGoogle(context);
                            },
                            icon: 'assets/icons/google.png',
                            iconWidth: 25,
                            iconHeight: 25,
                          ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
