import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/page/sign_up/sign_up.dart';
import 'package:e_commerce_training/src/page/sign_up/sign_up_cubit.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/widget/button_widget.dart';
import 'package:e_commerce_training/src/widget/custom_appbar.dart';
import 'package:e_commerce_training/src/widget/pending_action.dart';
import 'package:e_commerce_training/src/widget/text_field_widget.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class SignUpPage extends StatefulWidget {
  const SignUpPage({Key? key}) : super(key: key);

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

class _SignUpPageState extends State<SignUpPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _rePasswordController = TextEditingController();
  final TextEditingController _referencesCodeController = TextEditingController();
  FocusNode _emailFocus = FocusNode();
  FocusNode _phoneFocus = FocusNode();
  FocusNode _nameFocus = FocusNode();
  FocusNode _passFocus = FocusNode();
  FocusNode _rePassFocus = FocusNode();
  FocusNode _referencesCodeFocus = FocusNode();
  late SignUpCubit _signUpCubit;

  @override
  void initState() {
    AppRepository repository = AppRepository();
    _signUpCubit = SignUpCubit(repository);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: appBar(
          context,
          R.string.sign_up.tr(),
        ),
        body: BlocProvider(
          create: (context) => _signUpCubit,
          child: BlocConsumer<SignUpCubit, SignUpState>(
            listener: (context, state) {
              if (state is SignUpFailure) {
                Util.showErrorSnackBar(context, state.error!);
              }
              if (state is SignUpSuccess) {
                Util.showToast(state.message);
                Util.popByTime(context, 2, result: Const.REFRESH);
              }
            },
            builder: (context, SignUpState state) {
              return Container(
                height: double.infinity,
                width: double.infinity,
                child: Stack(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () => Util.hideKeyboard(context),
                      child: SingleChildScrollView(
                        padding: EdgeInsets.only(top: 40),
                        child: Column(children: <Widget>[
                          buildInputName(context, state),
                          buildInputPhoneNumber(context, state),
                          buildInputEmail(context, state),
                          buildInputPassword(context, state),
                          buildInputRePassword(context, state),
                          buildReferencesCode(context, state),
                          SizedBox(
                            height: 20,
                          ),
                          buildSignUp(state, context),
                        ]),
                      ),
                    ),
                    Visibility(
                      visible: state is SignUpLoading,
                      child: PendingAction(),
                    ),
                  ],
                ),
              );
            },
          ),
        ));
  }

  Widget buildSignUp(SignUpState state, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: ButtonWidget(
        title: R.string.sign_up.tr(),
        onPressed: () => _signUpCubit.signUp(
            name: _nameController.text,
            phoneNumber: _phoneController.text,
            email: _emailController.text,
            password: _passwordController.text,
            passwordConfirmation: _rePasswordController.text),
      ),
    );
  }

  Widget buildInputName(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        isEnable: !(state is SignUpLoading),
        controller: _nameController,
        focusNode: _nameFocus,
        labelText: R.string.name.tr() + " (*)",
        hintText: R.string.input_name.tr(),
        errorText: _signUpCubit.errorName,
        onChanged: (text) => _signUpCubit.validateName,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => Util.navigateNextFocusChange(
                  context,
                  _nameFocus,
                  _phoneFocus,
                ),
      ),
    );
  }

  Widget buildInputPhoneNumber(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        isEnable: !(state is SignUpLoading),
        controller: _phoneController,
        focusNode: _phoneFocus,
        keyboardType: TextInputType.phone,
        labelText: R.string.phone_number_1.tr() + " (*)",
        hintText: R.string.input_phone.tr(),
        errorText: _signUpCubit.errorPhone,
        onChanged: (text) => _signUpCubit.validatePhoneNumber,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => Util.navigateNextFocusChange(
                  context,
                  _phoneFocus,
                  _emailFocus,
                ),
      ),
    );
  }

  Widget buildInputEmail(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        isEnable: !(state is SignUpLoading),
        controller: _emailController,
        focusNode: _emailFocus,
        keyboardType: TextInputType.emailAddress,
        labelText: R.string.email.tr(),
        hintText: R.string.input_email.tr(),
        errorText: _signUpCubit.errorEmail,
        onChanged: (text) => _signUpCubit.validateEmail,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => Util.navigateNextFocusChange(
                  context,
                  _emailFocus,
                  _passFocus,
                ),
      ),
    );
  }

  Padding buildInputPassword(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        isEnable: !(state is SignUpLoading),
        controller: _passwordController,
        isPassword: true,
        focusNode: _passFocus,
        labelText: R.string.password.tr() + " (*)",
        hintText: R.string.input_pass.tr(),
        errorText: _signUpCubit.errorPass,
        onChanged: (text) => _signUpCubit.validatePassword,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => Util.navigateNextFocusChange(
                  context,
                  _passFocus,
                  _rePassFocus,
                ),
      ),
    );
  }

  Padding buildInputRePassword(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        controller: _rePasswordController,
        textInputAction: TextInputAction.go,
        isPassword: true,
        focusNode: _rePassFocus,
        labelText: R.string.confirm_password.tr() + " (*)",
        hintText: R.string.input_re_pass.tr(),
        errorText: _signUpCubit.errorConfirmPass,
        onChanged: (text) => _signUpCubit.validateConfirmPassword,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => _signUpCubit.signUp(
                name: _nameController.text,
                phoneNumber: _phoneController.text,
                email: _emailController.text,
                password: _passwordController.text,
                passwordConfirmation: _rePasswordController.text),
      ),
    );
  }

  Padding buildReferencesCode(BuildContext context, SignUpState state) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 8.0, 15, 0.0),
      child: TextFieldWidget(
        isEnable: !(state is SignUpLoading),
        controller: _referencesCodeController,
        focusNode: _referencesCodeFocus,
        labelText: R.string.references_code.tr(),
        hintText: R.string.input_references_code.tr(),
        errorText: _signUpCubit.errorPass,
        onChanged: (text) => _signUpCubit.validatePassword,
        onSubmitted: state is SignUpLoading
            ? null
            : (_) => Util.navigateNextFocusChange(
                  context,
                  _rePassFocus,
                  _referencesCodeFocus,
                ),
      ),
    );
  }
}
