import 'package:food_delivery_client/core/helpers/formatters.dart';
import 'package:food_delivery_client/core/helpers/validator_helpers.dart';
import 'package:food_delivery_client/feature/auth/domain/usecases/login_usecase.dart';
import 'package:food_delivery_client/feature/auth/presentation/pages/login_page/widgets/welcome_text.dart';
import 'package:food_delivery_client/feature/common/presentation/widgets/app_text_form_field.dart';

import '../../../../../../food_delivery_client.dart';
import '../../../blocs/login_bloc/login_bloc.dart';

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

  @override
  State<WLoginBody> createState() => _WLoginBodyState();
}

class _WLoginBodyState extends State<WLoginBody> {
  late TextEditingController _phoneNumberController;
  late TextEditingController _passwordController;
  final _formKey = GlobalKey<FormState>();
  bool _isValidForm = false;

  void _validateForm() {
    final isValid = _formKey.currentState?.validate() ?? false;
    if (isValid != _isValidForm) {
      setState(() {
        _isValidForm = isValid;
      });
    }
  }

  @override
  void initState() {
    _phoneNumberController = TextEditingController();
    _passwordController = TextEditingController();
    _passwordController.addListener(_validateForm);
    _phoneNumberController.addListener(_validateForm);
    super.initState();
  }

  @override
  void dispose() {
    _phoneNumberController.removeListener(_validateForm);
    _passwordController.removeListener(_validateForm);
    _phoneNumberController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LoginBloc, LoginState>(
      listenWhen: (previous, current) => previous.status != current.status,
      listener: (context, state) {
        if (state.status.isLoaded()) {
          context.go(Routes.main);
        }
      },
      builder: (context, state) {
        return Form(
          key: _formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: WLayout(
            top: false,
            left: false,
            right: false,
            child: Scaffold(
              body: Stack(
                children: [
                  SizedBox(
                    width: context.w,
                    child: SvgPicture.asset(
                      AppIcons.icLogin,
                      fit: BoxFit.fitWidth,
                    ),
                  ),
                  Positioned(
                    child: Material(
                      color: AppColors.cTransparent,
                      child: SingleChildScrollView(
                        keyboardDismissBehavior:
                            ScrollViewKeyboardDismissBehavior.onDrag,
                        child:
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                30.verticalSpace,
                                //WBackButton(),
                                60.verticalSpace,
                                WelcomeText(
                                  text: context.loc.welcome_to_volt(
                                    AppLocaleKeys.appName,
                                  ),
                                ),
                                8.verticalSpace,
                                Text(
                                  context.loc.please_login,
                                  style: AppTextStyles.size14Regular.copyWith(
                                    color: AppColors.cA7AEC1,
                                    height: 1.6,
                                  ),
                                ),
                                54.verticalSpace,
                                Text(
                                  context.loc.email_or_phone,
                                  style:
                                      context.appThemeTextStyles.size16Medium,
                                ),
                                10.verticalSpace,
                                AppTextFormField(
                                  prefixIcon: Text(
                                    "+ 998",
                                    style: context
                                        .appThemeTextStyles
                                        .size14Regular,
                                  ),
                                  controller: _phoneNumberController,
                                  hintText: context.loc.enter_email_or_phone,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                    Formatters.phoneFormatter,
                                    LengthLimitingTextInputFormatter(12),
                                  ],
                                  validator: (value) {
                                    return Validators.validatePhoneNumber(
                                      _phoneNumberController.text.trim(),
                                    );
                                  },
                                ),
                                20.verticalSpace,
                                Text(
                                  context.loc.password,
                                  style:
                                      context.appThemeTextStyles.size16Medium,
                                ),
                                10.verticalSpace,
                                AppTextFormField(
                                  obscureText: true,
                                  controller: _passwordController,
                                  hintText: context.loc.enter_password,
                                  validator: (value) {
                                    return Validators.validatePassword(
                                      _passwordController.text.trim(),
                                    );
                                  },
                                ),
                                10.verticalSpace,
                                Align(
                                  alignment: AlignmentGeometry.centerRight,
                                  child: TextButton(
                                    onPressed: () {
                                      context.push(Routes.forgotPassword);
                                    },
                                    child: Text(
                                      context.loc.forgot_password,
                                      style: AppTextStyles.size14Regular
                                          .copyWith(color: AppColors.cFF6F00),
                                    ),
                                  ),
                                ),
                                60.verticalSpace,
                                AppButton(
                                  name: context.loc.login,
                                  isActive: _isValidForm,
                                  isLoading: state.status.isLoading(),
                                  onPressed: () {
                                    if (_formKey.currentState?.validate() ??
                                        false) {
                                      context.read<LoginBloc>().add(
                                        LoginEvent.login(
                                          LoginParams(
                                            password: _passwordController.text
                                                .trim(),
                                            phoneNumber:
                                                "+998${_phoneNumberController.text.trim().replaceAll(" ", "")}",
                                          ),
                                        ),
                                      );
                                    }
                                  },
                                ),
                                15.verticalSpace,
                                Align(
                                  alignment: AlignmentGeometry.center,
                                  child: RichText(
                                    text: TextSpan(
                                      text: context.loc.dont_have_account,
                                      style: context
                                          .appThemeTextStyles
                                          .size14Regular,
                                      children: [
                                        WidgetSpan(
                                          baseline: TextBaseline.alphabetic,
                                          alignment:
                                              PlaceholderAlignment.baseline,
                                          child: TextButton(
                                            onPressed: () {},
                                            style: ButtonStyle(
                                              shadowColor:
                                                  WidgetStatePropertyAll(
                                                    AppColors.cFF6F00
                                                        .newWithOpacity(.2),
                                                  ),
                                              padding: WidgetStatePropertyAll(
                                                EdgeInsets.symmetric(
                                                  horizontal: 4,
                                                ),
                                              ),
                                            ),
                                            child: Text(
                                              context.loc.register,
                                              style: AppTextStyles.size14Bold
                                                  .copyWith(
                                                    color: AppColors.cFF6F00,
                                                  ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ).paddingOnly(
                              left: 24,
                              right: 24,
                              top: context.mq.viewPadding.top,
                              bottom: context.mq.viewPadding.bottom,
                            ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
