// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/data/model/ai/credit_model.dart';

import 'package:hoshan/ui/screens/auth/login/bloc/login_bloc.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/button/loading_button.dart';
import 'package:hoshan/ui/widgets/components/snackbar/snackbar_manager.dart';
import 'package:hoshan/ui/widgets/components/text/auth_text_field.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController username = TextEditingController();
  final TextEditingController password = TextEditingController();
  bool typeUser = false;
  bool typePassword = false;
  ValueNotifier<String?> passwodError = ValueNotifier(null);
  ValueNotifier<String?> usernameError = ValueNotifier(null);

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LoginBloc, LoginState>(
      listener: (context, state) async {
        if (state is LoginSuccess) {
          await context.read<UserInfoCubit>().getUserInfo();
          context.read<UserInfoCubit>().changeCredit(CreditModel(
              credit: UserInfoCubit.userInfoModel.credit,
              freeCredit: UserInfoCubit.userInfoModel.freeCredit));
          context.go(Routes.home);
        }
        if (state is LoginFail) {
          switch (state.error) {
            case 'کاربر یافت نشد':
              usernameError.value = state.error;
              break;
            case 'رمز عبور اشتباه است':
              passwodError.value = state.error;
              break;
            default:
              SnackBarManager(context, id: 'server-login').show(
                  message: 'خطا از طرف سرور لحظاتی دیگر دوباره امتحان کنید',
                  status: SnackBarStatus.error);
          }
        }
      },
      builder: (context, state) {
        return Column(
          children: [
            Text(
              '.نام کاربری و رمز عبور خود را وارد کنید',
              style: AppTextStyles.body4.copyWith(
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.onSurface),
            ),
            Padding(
              padding: const EdgeInsets.all(18.0),
              child: Directionality(
                  textDirection: TextDirection.rtl,
                  child: ValueListenableBuilder(
                      valueListenable: usernameError,
                      builder: (context, error, _) {
                        return AuthTextField(
                          hintText: 'مثال: Ali',
                          label: 'نام کاربری',
                          textInputAction: TextInputAction.next,
                          controller: username,
                          error: error != null
                              ? Row(
                                  children: [
                                    Icon(
                                      Icons.warning_amber_rounded,
                                      color: AppColors.red.defaultShade,
                                      size: 16,
                                    ),
                                    const SizedBox(
                                      width: 8,
                                    ),
                                    Text(
                                      error,
                                      style: AppTextStyles.body5.copyWith(
                                          color: AppColors.red.defaultShade),
                                    ),
                                  ],
                                )
                              : null,
                          onChange: (val) {
                            usernameError.value = null;
                            setState(() {
                              typeUser = val.length > 2 ? true : false;
                            });
                          },
                        );
                      })),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(18, 0, 18, 12),
              child: Directionality(
                  textDirection: TextDirection.rtl,
                  child: ValueListenableBuilder(
                      valueListenable: passwodError,
                      builder: (context, error, _) {
                        return AuthTextField(
                          label: 'رمز عبور',
                          isPassword: true,
                          controller: password,
                          onChange: (val) {
                            passwodError.value = null;

                            setState(() {
                              typePassword = val.length >= 8 ? true : false;
                            });
                          },
                          error: error != null
                              ? Row(
                                  children: [
                                    Icon(
                                      Icons.warning_amber_rounded,
                                      color: AppColors.red.defaultShade,
                                      size: 16,
                                    ),
                                    const SizedBox(
                                      width: 8,
                                    ),
                                    Text(
                                      error,
                                      style: AppTextStyles.body5.copyWith(
                                          color: AppColors.red.defaultShade),
                                    ),
                                  ],
                                )
                              : null,
                        );
                      })),
            ),
            // GestureDetector(
            //   onTap: () {},
            //   child: SizedBox(
            //     width: MediaQuery.sizeOf(context).width,
            //     child: Padding(
            //       padding: const EdgeInsets.only(bottom: 18, right: 20),
            //       child: Text(
            //         'رمز عبور خود را فراموش کردید؟',
            //         textAlign: TextAlign.right,
            //         style: AppTextStyles.body5.copyWith(
            //             fontWeight: FontWeight.bold,
            //             color: AppColors.primaryColor.defaultShade),
            //       ),
            //     ),
            //   ),
            // ),
            const SizedBox(
              height: 24,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: LoadingButton(
                  width: MediaQuery.sizeOf(context).width,
                  height: 48,
                  radius: 100,
                  loading: state is LoginLoading || state is LoginSuccess,
                  onPressed: typeUser &&
                          typePassword &&
                          usernameError.value == null &&
                          passwodError.value == null
                      ? () {
                          context.read<LoginBloc>().add(LoginWithPassword(
                              username: username.text,
                              password: password.text));
                        }
                      : null,
                  child: Text(
                    'ورود',
                    style: AppTextStyles.body4.copyWith(color: Colors.white),
                  )),
            ),
          ],
        );
      },
    );
  }
}
