import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:design_system/design_system.dart';
import 'package:staff_authentication/src/domain/ui_entities/auth_mode.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_event.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_state.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_bloc.dart';
import '../widgets/phone_verification_page/phone_input.dart';
import '../widgets/phone_verification_page/otp_verification.dart';
import 'package:staff_authentication/staff_authentication.dart';
import '../navigation/auth_navigator.dart'; // Import the extension

/// A combined page for phone number entry and OTP verification.
///
/// This page coordinates the authentication flow by switching between
/// [PhoneInput] and [OtpVerification] based on the current [AuthState].
class PhoneVerificationPage extends StatelessWidget {
  /// The authentication mode (login or signup).
  final AuthMode mode;

  /// Creates a [PhoneVerificationPage].
  const PhoneVerificationPage({super.key, required this.mode});

  /// Handles the request to send a verification code to the provided phone number.
  void _onSendCode({
    required BuildContext context,
    required String phoneNumber,
  }) {
    if (phoneNumber.length == 10) {
      BlocProvider.of<AuthBloc>(
        context,
      ).add(AuthSignInRequested(phoneNumber: '+1$phoneNumber', mode: mode));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            t.staff_authentication.phone_verification_page.validation_error,
          ),
        ),
      );
    }
  }

  /// Handles the submission of the OTP code.
  void _onOtpSubmitted({
    required BuildContext context,
    required String otp,
    required String verificationId,
  }) {
    BlocProvider.of<AuthBloc>(
      context,
    ).add(
      AuthOtpSubmitted(
        verificationId: verificationId,
        smsCode: otp,
        mode: mode,
      ),
    );
  }

  /// Handles the request to resend the verification code using the phone number in the state.
  void _onResend({required BuildContext context}) {
    BlocProvider.of<AuthBloc>(context).add(AuthSignInRequested(mode: mode));
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<AuthBloc>(
      create: (BuildContext context) => Modular.get<AuthBloc>(),
      child: Builder(
        builder: (BuildContext context) {
          return BlocListener<AuthBloc, AuthState>(
            listener: (BuildContext context, AuthState state) {
              if (state.status == AuthStatus.authenticated) {
                if (state.mode == AuthMode.signup) {
                  Modular.to.pushReplacementProfileSetup();
                } else {
                  Modular.to.pushWorkerHome();
                }
              } else if (state.status == AuthStatus.error &&
                  state.mode == AuthMode.signup) {
                final String message = state.errorMessage ?? '';
                if (message.contains('staff profile')) {
                  Modular.to.pushReplacementNamed(
                    './phone-verification',
                    arguments: <String, String>{
                      'mode': AuthMode.login.name,
                    },
                  );
                } else if (message.contains('not authorized')) {
                  Modular.to.pop();
                }
              }
            },
            child: BlocBuilder<AuthBloc, AuthState>(
              builder: (BuildContext context, AuthState state) {
                // Check if we are in the OTP step
                final bool isOtpStep =
                    state.status == AuthStatus.codeSent ||
                    (state.status == AuthStatus.error &&
                        state.verificationId != null) ||
                    (state.status == AuthStatus.loading &&
                        state.verificationId != null);

                return Scaffold(
                  appBar: const UiAppBar(
                    centerTitle: true,
                    showBackButton: true,
                  ),
                  body: SafeArea(
                    child: isOtpStep
                        ? OtpVerification(
                            state: state,
                            onOtpSubmitted: (String otp) => _onOtpSubmitted(
                              context: context,
                              otp: otp,
                              verificationId: state.verificationId ?? '',
                            ),
                            onResend: () => _onResend(context: context),
                            onContinue: () => _onOtpSubmitted(
                              context: context,
                              otp: state.otp,
                              verificationId: state.verificationId ?? '',
                            ),
                          )
                        : PhoneInput(
                            state: state,
                            onSendCode: () => _onSendCode(
                              context: context,
                              phoneNumber: state.phoneNumber,
                            ),
                          ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}
