import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:initial_folder/providers/registrasi_google_provider.dart';
import 'package:initial_folder/screens/login/login_with_email/login_email_screen.dart';
import 'package:initial_folder/screens/registrasi/registrasi_with_email/success_regis_screen.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/providers/auth_provider.dart';
import 'package:initial_folder/screens/login/login_screen.dart';
import 'package:initial_folder/screens/registrasi/registrasi_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/footer.dart';
import 'package:initial_folder/widgets/login_regist/header.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/size_config.dart';

import '../../../widgets/login_regist/failed_login.dart';
import '../../login/components/get_user_data.dart';

class RegistrationEmail extends StatefulWidget {
  static String routeName = "/registration_email";
  RegistrationEmail({
    Key? key,
  }) : super(key: key);

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

class _RegistrationEmailState extends State<RegistrationEmail> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController nameController = TextEditingController(text: '');

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

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

  final TextEditingController passwordController =
      TextEditingController(text: '');
  final TextEditingController rePasswordController =
      TextEditingController(text: '');
  bool isLoading = false;
  bool failed = false;
  bool _isObscure = true;
  bool _isObscure1 = true;

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    AuthProvider authProvider = Provider.of<AuthProvider>(context);

    final userProvider = Provider.of<RegistrasiGoogleProvider>(context);
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    nameController.text = nameController.text.isNotEmpty
        ? nameController.text
        : (args?['nama'] ?? userProvider.name ?? '');
    emailController.text = emailController.text.isNotEmpty
        ? emailController.text
        : (args?['email'] ?? userProvider.email ?? '');

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

      try {
        if (phoneNumberController.text.length > 16) {
          throw ('Failed\n\nNomor HP maksimal hanya 15 angka');
        }
        if (await authProvider.register(
          name: nameController.text,
          email: emailController.text,
          password: passwordController.text,
          phoneNumber: phoneNumberController.text,
        )) {
          await UsersInfo().setEmail(emailController.text);
          await authProvider
              .login(
            email: emailController.text,
            password: passwordController.text,
          )
              .then((value) async {
            Condition.loginEmail = true;
            await getUserData(context);
            Navigator.of(context).pushNamedAndRemoveUntil(
                RegisSuccess.routeName, (Route<dynamic> route) => false);
          });
        }
      } catch (e) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: Container(
              height: 90,
              alignment: AlignmentDirectional.topStart,
              child: Padding(
                padding: EdgeInsets.only(
                    top: getProportionateScreenHeight(15),
                    right: getProportionateScreenHeight(10)),
                child: Text(
                  e.toString(),
                  style: primaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(11),
                    letterSpacing: 1,
                  ),
                ),
              ),
            ),
            actions: [
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Padding(
                  padding: EdgeInsets.only(
                      right: getProportionateScreenHeight(15),
                      bottom: getProportionateScreenHeight(2)),
                  child: Text(
                    'Ok',
                    style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: primaryColor,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }

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

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

    Widget form() {
      Widget nameInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: nameController,
          hinttext: 'Masukan nama lengkap',
          title: 'Nama Lengkap',
          validate: validateName,
        );
      }

      Widget emailInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: emailController,
          hinttext: 'Masukan email',
          title: 'Email',
          validate: validateEmail,
        );
      }

      Widget reEmailInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: reEmailController,
          hinttext: 'Masukan konfirmasi email',
          title: 'Konfirmasi Email',
          validate: (String? value) {
            return validateReEmail(value, emailController.text);
          },
        );
      }

      Widget phoneNumberInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: phoneNumberController,
          hinttext: 'Masukan no hp',
          title: 'No Telepon',
          validate: validatePhone,
        );
      }

      Widget passwordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: passwordController,
          hinttext: 'Masukan 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,
                    )),
        );
      }

      Widget rePasswordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: rePasswordController,
          hinttext: 'Masukan password',
          title: 'Konfirmasi Password',
          obscuretext: _isObscure1,
          suffix: GestureDetector(
              onTap: () => setState(() {
                    _isObscure1 = !_isObscure1;
                  }),
              child: _isObscure1
                  ? Icon(
                      FeatherIcons.eyeOff,
                      color: secondaryColor,
                      size: 18,
                    )
                  : Icon(
                      FeatherIcons.eye,
                      color: secondaryColor,
                      size: 18,
                    )),
          validate: (String? value) {
            return validateRePassword(value, passwordController.text);
          },
        );
      }

      Widget button() {
        return Padding(
          padding: EdgeInsets.only(
              left: getProportionateScreenWidth(15),
              right: getProportionateScreenWidth(15),
              top: getProportionateScreenHeight(3)),
          child: isLoading
              ? LoadingButton(
                  backgroundButtonColor: primaryColor,
                  textButtonColor: baruTextutih,
                )
              : DefaultButton(
                  text: 'Register',
                  press: _validateInputs,
                ),
        );
      }

      return Form(
        key: _formKey,
        child: Column(
          children: [
            nameInput(),
            emailInput(),
            reEmailInput(),
            phoneNumberInput(),
            passwordInput(),
            rePasswordInput(),
            SizedBox(
              height: getProportionateScreenHeight(8),
            ),
            button(),
          ],
        ),
      );
    }

    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: getProportionateScreenHeight(25),
              ),
              Container(
                padding: EdgeInsets.only(
                    right: getProportionateScreenWidth(25),
                    left: getProportionateScreenWidth(25)),
                child: Align(
                    alignment: Alignment.center,
                    child: Text('Register',
                        style: thirdTextStyle.copyWith(
                            // color: baruTexthitam,
                            fontWeight: FontWeight.w900,
                            fontSize: getProportionateScreenWidth(20),
                            letterSpacing: 0.5))),
              ),
              SizedBox(
                height: getProportionateScreenHeight(32),
              ),
              form(),
              SizedBox(height: getProportionateScreenHeight(32)),
              Footer(
                textOne: 'Sudah punya akun? ',
                textTwo: 'Log in',
                route: LoginEmail.routeName,
                height: 14,
              )
            ],
          ),
        ),
      ),
    );
  }
}
