import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/widgets/ui_kit/dialogs/kw_dialog.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_loading_overlay.dart';
import 'package:krow/features/profile/email_verification/domain/bloc/email_verification_bloc.dart';

class BottomControlButton extends StatelessWidget {
  const BottomControlButton({super.key});

  void _listenHandler(BuildContext context, EmailVerificationState state) {
    if (state.reAuthRequirement == ReAuthRequirement.none) return;

    KwDialog.show(
      context: context,
      icon: Assets.images.icons.alertTriangle,
      state: KwDialogState.negative,
      barrierDismissible: false,
      title: 'additional_action_needed'.tr(),
      message: state.reAuthRequirement == ReAuthRequirement.recent
          ? 'email_verification_security_sensitive'.tr(args: [state.userPhone])
          : 'unable_to_validate_email_status'.tr(),
      primaryButtonLabel: 'Continue'.tr(),
      onPrimaryButtonPressed: (dialogContext) async {
        final isReAuthenticated = await dialogContext.pushRoute<bool>(
          PhoneReLoginFlowRoute(userPhone: state.userPhone),
        );

        if (dialogContext.mounted) Navigator.maybePop(dialogContext);

        if (isReAuthenticated == true &&
            context.mounted &&
            state.reAuthRequirement == ReAuthRequirement.recent) {
          context
              .read<EmailVerificationBloc>()
              .add(const ResendVerificationEmail());
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<EmailVerificationBloc, EmailVerificationState>(
      buildWhen: (previous, current) => previous.status != current.status,
      listenWhen: (previous, current) =>
          previous.reAuthRequirement != current.reAuthRequirement,
      listener: _listenHandler,
      builder: (context, state) {
        return KwLoadingOverlay(
          shouldShowLoading: state.status == StateStatus.loading,
          child: KwButton.primary(
            label: 'Continue'.tr(),
            disabled: state.status != StateStatus.success,
            onPressed: () {
              context.maybePop(true);
            },
          ),
        );
      },
    );
  }
}
