import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/features/auth/login/constants/mail_input_decoration.dart';
import 'package:hamlemuhcrm/features/auth/login/constants/password_input_decoration.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/constants/login_constants.dart';
import 'package:hamlemuhcrm/features/auth/login/view/login_view_mixin.dart';
import 'package:hamlemuhcrm/features/home/view/home_custom.dart';

import '../../../../core/constants/color_constants.dart';
import '../../../../core/utility/toast_manager.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> with LoginViewMixin {
  final _loginKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      backgroundColor: ColorsConstants.instance.backgroundColor,
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _logo,
            _emptyContainerTopSpace,
            _formContainer,
            _emptyVerTextSpace,
            _verText,
          ],
        ),
      ),
    );
  }

  AppBar appBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
    );
  }

  Widget get _logo => SizedBox(
      height: context.dynamicHeight(0.185),
      child: Image.asset('assets/images/applogo.png'));

  Widget get _emptyTfHeightSpace =>
      SizedBox(height: context.dynamicHeight(0.013));

  Widget get _emptyVerTextSpace =>
      SizedBox(height: context.dynamicHeight(0.02));

  Widget get _verText => Text(
        LoginConstants.verInfoText,
        style: FontStyles.instance.versionTxt,
      );

  void _navigateToHome() {
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => HomeCustom()));
  }

  Widget get _emptyContainerTopSpace => SizedBox(
        height: context.dynamicHeight(0.08),
      );

  Widget get _formContainer => Container(
      margin: EdgeInsets.symmetric(
          horizontal: context.dynamicWidth(0.15)), //form ekranı sağ sol boşluk
      padding:
          EdgeInsets.all(context.dynamicHeight(0.025)), //iç boşluklar (form)
      height: context.dynamicHeight(0.4),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25),
        color: ColorsConstants.instance.backgroundColor,
        border:
            Border.all(color: ColorsConstants.instance.baseTheme, width: 1.5),
      ),
      child: _formLogic);

  Widget get _formLogic => BlocConsumer<LoginCubit, LoginState>(
        listener: (context, state) {
          if (state.isLoggedIn &&
              state.isComplete &&
              !state.isLoading &&
              !state.isError &&
              !state.isCorrect &&
              !state.isFieldEmpty) {
            ToastManager.instance.toastMessageService('Giriş Başarılı');
            _navigateToHome();
          } else if (state.isFieldEmpty & !state.isLoading &&
              !state.isError &&
              !state.isComplete &&
              !state.isCorrect &&
              !state.isLoggedIn) {
            ToastManager.instance.toastMessageService("Boş bırakılamaz");
          } else if (state.isError &&
              !state.isLoggedIn &&
              !state.isComplete &&
              !state.isFieldEmpty) {
            ToastManager.instance.toastMessageService("Sunucu bağlantı hatası");
          } else if (state.isCorrect && !state.isFieldEmpty && !state.isError) {
            ToastManager.instance
                .toastMessageService('Kullanıcı Adı Veya Şifre Yanlış !');
          }
        },
        builder: (context, state) {
          return Form(
            key: _loginKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _tfMail,
                _emptyTfHeightSpace,
                _tfPassword,
                _rememberMeCheck,
                _loginButton(context, state),
                //_registerButton,
                //_changePasswordButton,
              ],
            ),
          );
        },
      );

  Widget get _tfMail => Container(
        height: context.dynamicHeight(0.065),
        decoration: BoxDecoration(
          color: ColorsConstants.instance.baseThemeV2,
          borderRadius: BorderRadius.circular(20),
        ),
        alignment: Alignment.center,
        child: TextFormField(
            controller: tfMail,
            keyboardType: TextInputType.emailAddress,
            magnifierConfiguration: TextMagnifierConfiguration.disabled,
            textInputAction: TextInputAction.next,
            inputFormatters: [LengthLimitingTextInputFormatter(40)],
            decoration: MailTextFieldInput(context)),
      );

  Widget get _tfPassword => Container(
        //Şifre
        alignment: Alignment.center,
        height: context.dynamicHeight(0.065),
        decoration: BoxDecoration(
          color: ColorsConstants.instance.baseThemeV2,
          borderRadius: BorderRadius.circular(20),
        ),
        child: ValueListenableBuilder<bool>(
          valueListenable: isVisible,
          builder: (context, value, child) => TextFormField(
            controller: tfPassword,
            obscureText: isVisible.value,
            magnifierConfiguration: TextMagnifierConfiguration.disabled,
            textInputAction: TextInputAction.done,
            inputFormatters: [LengthLimitingTextInputFormatter(20)],
            decoration:
                PasswordTextFieldInput(context, isVisible: isVisible.value, () {
              isVisible.value = !isVisible.value;
              debugPrint(isVisible.value.toString());
            }),
          ),
        ),
      );

  Widget get _rememberMeCheck => Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          ValueListenableBuilder<bool>(
            valueListenable: checkNotifier,
            builder: (context, value, child) {
              return Checkbox(
                  value: checkNotifier.value,
                  checkColor: ColorsConstants.instance.baseTheme,
                  activeColor: ColorsConstants.instance.shadowColor,
                  onChanged: (value) {
                    checkNotifier.value = value ?? false;
                    debugPrint(checkNotifier.value.toString());
                  });
            },
          ),
          const Text(
            LoginConstants.loginRememberMeText,
            style: TextStyle(fontSize: 13, color: Colors.black87),
          ),
        ],
      );

  Widget _loginButton(BuildContext context, LoginState state) {
    return ElevatedButton(
      onPressed: !state.isLoading
          ? () {
              _loginKey.currentState!.save();
              context.read<LoginCubit>().loginOl(tfMail.text, tfPassword.text);
            }
          : null,
      style: ElevatedButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme),
      child: Center(
        child: Text(LoginConstants.loginButtonText,
            style: FontStyles.instance.girisBtnYazi),
      ),
    );
  }
}

// NOTE : Kayıt Olma ve Şifremi Unuttum bu versiyon için geçerli değil

//   Widget get _registerButton => GestureDetector(
//         onTap: () {
//           // debugPrint('Hesap oluştura tıklandı.');
//         },
//         child: Container(
//           height: context.dynamicHeight(0.04),
//           alignment: Alignment.center,
//           decoration: BoxDecoration(color: Colors.grey.shade200),
//           child: Text(
//             LoginConstants.loginRegisterText,
//             style: FontStyles.instance.ddYazi,
//           ),
//         ),
//       );

//   Widget get _changePasswordButton => GestureDetector(
//         onTap: () async {
//           // debugPrint('Şifremi unuttum tıklandı.');
//         },
//         child: Container(
//           height: context.dynamicHeight(0.04),
//           alignment: Alignment.center,
//           decoration: BoxDecoration(color: Colors.grey.shade200),
//           child: Text(
//             LoginConstants.loginForgotPasswordText,
//             style: FontStyles.instance.ddYazi,
//           ),
//         ),
//       );
// }

