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/forgot_password/forgot_password_page.dart';
import 'package:e_commerce_training/src/page/home/home.dart';
import 'package:e_commerce_training/src/page/login/login_cubit.dart';
import 'package:e_commerce_training/src/page/login/login_state.dart';
import 'package:e_commerce_training/src/page/sign_up/sign_up_page.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/navigation_util.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:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_localization/easy_localization.dart';

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

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

class _LoginPageState extends State<LoginPage> {
  late LoginCubit _loginCubit;
  late TextEditingController _emailController;
  late TextEditingController _phoneController;
  late TextEditingController _id;
  late TextEditingController _passwordController;
  late FocusNode _usernameFocus;
  late FocusNode _phoneFocus;
  late FocusNode _passwordFocus;

  @override
  void initState() {
    AppRepository repository = AppRepository();
    _loginCubit = LoginCubit(repository);
    _emailController = TextEditingController();
    _phoneController = TextEditingController();
    _passwordController = TextEditingController();
    _usernameFocus = FocusNode();
    _phoneFocus = FocusNode();
    _passwordFocus = FocusNode();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: R.color.white,
      appBar: appBar(
        context,
        R.string.sign_in.tr(),
      ),
      body: BlocProvider(
        create: (context) => _loginCubit,
        child: BlocConsumer<LoginCubit, LoginState>(
          listener: (context, state) {
            if (state is LoginSuccess) {
              Util.showToast(state.message);
              NavigationUtil.pop(context, result: Const.REFRESH);
            }
            if (state is LoginFailure) {
              Util.showErrorSnackBar(context, state.error!);
            }
          },
          builder: (context, state) {
            return buildPage(context, state);
          },
        ),
      ),
    );
  }

  Widget buildPage(BuildContext context, LoginState state) {
    return GestureDetector(
      onTap: () => Util.hideKeyboard(context),
      child: Stack(
        children: <Widget>[
          SingleChildScrollView(
            child: Container(
              margin: EdgeInsets.only(top: 50),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                      padding: EdgeInsets.symmetric(horizontal: 20),
                      child: Text(
                        R.string.sign_in.tr(),
                        style: TextStyle(
                          fontSize: 30,
                          color: R.color.primaryColor,
                        ),
                      )),
                  SizedBox(
                    height: 50.h,
                  ),
                  buildInputPhone(context),
                  SizedBox(height: 10),
                  buildInputPassword(context),
                  SizedBox(height: 10),
                  buildForgetPassword(context),
                  SizedBox(height: 10),
                  buildSignIn(state, context),
                  SizedBox(height: 20),
                  Center(
                    child: RichText(
                      text: TextSpan(text: R.string.no_account.tr(), style: TextStyle(fontSize: 14.sp, color: R.color.grey), children: <TextSpan>[
                        TextSpan(
                            text: R.string.register_account.tr(),
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: R.color.primaryColor,
                              fontWeight: FontWeight.w400,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                state is LoginLoading ? null : Util.navigatePage(context, SignUpPage());
                              }),
                      ]),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: state is LoginLoading,
            child: PendingAction(),
          ),
        ],
      ),
    );
  }

  Widget buildSignIn(LoginState state, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: ButtonWidget(
        title: R.string.sign_in.tr(),
        backgroundColor: R.color.primaryColor,
        onPressed: () => state is LoginLoading
            ? null
            : _loginCubit.login(
                _phoneController.text,
                _passwordController.text,
              ),
      ),
    );
  }

  Widget buildRegister(LoginState state, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: ButtonWidget(
        title: R.string.sign_up.tr(),
        backgroundColor: Colors.lightBlue[50],
        textColor: R.color.primaryColor,
        onPressed: () => state is LoginLoading ? null : Util.navigatePage(context, SignUpPage()),
      ),
    );
  }

  Padding buildInputPassword(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
      child: TextFieldWidget(
        controller: _passwordController,
        textInputAction: TextInputAction.done,
        keyboardType: TextInputType.text,
        labelText: R.string.password.tr(),
        hintText: R.string.input_pass.tr(),
        isPassword: true,
        errorText: _loginCubit.errorPass,
        onChanged: (text) => _loginCubit.validatePass(text!),
        focusNode: _passwordFocus,
        onSubmitted: (text) => _loginCubit.login(_phoneController.text, _passwordController.text),
      ),
    );
  }

  Padding buildInputEmail(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
      child: TextFieldWidget(
        focusNode: _usernameFocus,
        controller: _emailController,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.emailAddress,
        errorText: _loginCubit.errorEmail,
        onChanged: (text) => _loginCubit.validateEmail,
        labelText: R.string.email.tr(),
        onSubmitted: (text) => Util.navigateNextFocusChange(context, _usernameFocus, _passwordFocus),
      ),
    );
  }

  Padding buildInputPhone(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
      child: TextFieldWidget(
        focusNode: _phoneFocus,
        controller: _phoneController,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.text,
        errorText: _loginCubit.errorPhone,
        hintText: R.string.input_email_or_phone_number.tr(),
        onChanged: (text) => _loginCubit.validatePhone,
        labelText: R.string.email_or_phone_number.tr(),
        onSubmitted: (text) => Util.navigateNextFocusChange(context, _phoneFocus, _passwordFocus),
      ),
    );
  }

  Widget buildForgetPassword(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: GestureDetector(
              onTap: () => Util.navigatePage(context, ForgotPassPage()),
              child: Container(
                alignment: Alignment.centerRight,
                child: Text(
                  R.string.forgot_password.tr(),
                  style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: R.color.primaryColor, decoration: TextDecoration.underline),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
