import 'package:farm_tpf/themes/app_dimension.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import '../../../authentication/bloc/authentication_bloc.dart';
import '../../../common/const_enum.dart';
import '../../../themes/app_colors.dart';
import '../../../themes/styles_text.dart';
import '../../../utils/app_images.dart';
import '../../../utils/helpers.dart';
import '../../../utils/utils.dart';
import '../../../utils/validators.dart';
import '../../custom_widgets/button/primary_button_widget.dart';
import '../../custom_widgets/textfield/text_field_normal.dart';
import 'cubit/login_cubit.dart';

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

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

class _LoginPageState extends State<LoginPage> {
  var loginBloc = LoginCubit();
  var loginErrorMessage = ValueNotifier('');

  @override
  void initState() {
    super.initState();
    if (kDebugMode) {
      loginBloc.usernameCtl.text = 'lecaoanhquoc';
      loginBloc.passwordCtl.text = '12345678';
    }
  }

  @override
  void dispose() {
    super.dispose();
    loginBloc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<LoginCubit, LoginState>(
      bloc: loginBloc,
      listener: (context, state) {
        if (state is LoginLoading) {
          Helpers.hideKeyboard(context);
          UtilWidget.showLoading();
        } else if (state is LoginFailure) {
          UtilWidget.hideLoading();
          loginErrorMessage.value = state.errorMessage;
          loginErrorMessage.notifyListeners();
        } else if (state is LoginSuccess) {
          UtilWidget.hideLoading();
          BlocProvider.of<AuthenticationBloc>(context).add(
            const AuthenticationStatusChanged(
              AuthenticationStatus.authenticated,
            ),
          );
        } else {
          UtilWidget.hideLoading();
        }
      },
      child: _widgetMainBody(),
    );
  }

  Widget _widgetMainBody() {
    return Scaffold(
      body: KeyboardDismisser(
        child: Container(
          decoration: BoxDecoration(
            color: AppColors.primary1,
          ),
          child: Stack(
            children: <Widget>[
              Positioned(
                top: 0,
                right: 0,
                left: 0,
                child: Container(
                  height: 370.h,
                  decoration: BoxDecoration(
                    color: AppColors.background1,
                    // image: const DecorationImage(
                    //   image: AssetImage(AssetPNG.backgroundLogin),
                    //   fit: BoxFit.cover,
                    // ),
                  ),
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                left: 0,
                child: Container(
                  height: 371.h,
                  decoration: BoxDecoration(
                    color: AppColors.primary1,
                    gradient: LinearGradient(
                      colors: [
                        AppColors.primary1,
                        AppColors.primary1.withOpacity(0),
                      ],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 140.h,
                right: 40.w,
                left: 40.w,
                child: Image.asset(
                  AssetPNG.logo,
                  height: 150,
                ),
              ),
              Positioned(
                bottom: 8,
                right: 8,
                left: 8,
                child: SafeArea(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(32.r),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16.r),
                    ),
                    child: Form(
                      key: loginBloc.formKey,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            'Đăng Nhập',
                            style: StylesText.header1,
                          ),
                          const SizedBox(
                            height: 9,
                          ),
                          Text(
                            'Nhập tài khoản và mật khẩu để đăng nhập',
                            style: StylesText.body6.copyWith(
                              color: AppColors.neutral2,
                            ),
                          ),
                          SizedBox(
                            height: 24.h,
                          ),
                          Text(
                            'Tài Khoản',
                            style: StylesText.body6,
                          ),
                          const SizedBox(
                            height: 4,
                          ),
                          TextFieldNormal(
                            controller: loginBloc.usernameCtl,
                            hint: 'Nhập tài khoản',
                            validator: (val) {
                              return Validators.validateNotNullOrEmpty(
                                val ?? '',
                                'Nhập tài khoản',
                              );
                            },
                          ),
                          const SizedBox(
                            height: 16,
                          ),
                          Text(
                            'Mật Khẩu',
                            style: StylesText.body6,
                          ),
                          const SizedBox(
                            height: 4,
                          ),
                          TextFieldNormal(
                            controller: loginBloc.passwordCtl,
                            hint: 'Nhập Mật Khẩu',
                            isPasswordField: true,
                            validator: (val) {
                              return Validators.validateNotNullOrEmpty(
                                val ?? '',
                                'Nhập Mật Khẩu',
                              );
                            },
                          ),
                          ValueListenableBuilder<String>(
                            valueListenable: loginErrorMessage,
                            builder: (context, errorMessage, _) {
                              if (Validators.stringNotNullOrEmpty(errorMessage)) {
                                return Container(
                                  decoration: BoxDecoration(
                                    color: AppColors.semantic7,
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  margin: const EdgeInsets.only(
                                    top: 16,
                                  ),
                                  padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                                  child: Row(
                                    children: [
                                      SvgPicture.asset(AssetSVG.icWarning),
                                      const SizedBox(
                                        width: 4,
                                      ),
                                      Text(
                                        errorMessage,
                                        style: StylesText.caption3.copyWith(
                                          color: AppColors.semantic6,
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              } else {
                                return const SizedBox.shrink();
                              }
                            },
                          ),
                          SizedBox(
                            height: 24.h,
                          ),
                          PrimaryButtonWidget(
                            title: 'Đăng Nhập',
                            onPressed: () => onPressedLogin(),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void onPressedRememberLogin(bool isRemember) {
    loginBloc.rememberMe(isRemember);
  }

  void onPressedForgotPassword() {}

  void onPressedLogin() {
    loginBloc.loginWithCredential();
  }
}
