import 'package:flutter_bloc/flutter_bloc.dart';

// ---------------- EVENTS ----------------
abstract class ForgotPasswordEvent {}

class EmailChanged extends ForgotPasswordEvent {
  final String email;
  EmailChanged(this.email);
}

class SendResetLink extends ForgotPasswordEvent {}

// ---------------- STATE ----------------
class ForgotPasswordState {
  final String email;
  final bool isValidEmail;
  final bool isLoading;
  final bool isSuccess;
  final String message;

  const ForgotPasswordState({
    required this.email,
    required this.isValidEmail,
    required this.isLoading,
    required this.isSuccess,
    required this.message,
  });

  ForgotPasswordState copyWith({
    String? email,
    bool? isValidEmail,
    bool? isLoading,
    bool? isSuccess,
    String? message,
  }) {
    return ForgotPasswordState(
      email: email ?? this.email,
      isValidEmail: isValidEmail ?? this.isValidEmail,
      isLoading: isLoading ?? this.isLoading,
      isSuccess: isSuccess ?? this.isSuccess,
      message: message ?? this.message,
    );
  }

  factory ForgotPasswordState.initial() => const ForgotPasswordState(
    email: '',
    isValidEmail: false,
    isLoading: false,
    isSuccess: false,
    message: '',
  );
}

// ---------------- BLOC ----------------
class ForgotPasswordBloc
    extends Bloc<ForgotPasswordEvent, ForgotPasswordState> {
  ForgotPasswordBloc() : super(ForgotPasswordState.initial()) {
    // when email changes
    on<EmailChanged>((event, emit) {
      final isValid = _isValidEmail(event.email);
      emit(state.copyWith(email: event.email, isValidEmail: isValid));
    });

    // when button clicked
    on<SendResetLink>((event, emit) async {
      if (!state.isValidEmail) return;

      emit(state.copyWith(isLoading: true, message: ''));
      await Future.delayed(const Duration(seconds: 2)); // simulate API delay
      emit(state.copyWith(
        isLoading: false,
        isSuccess: true,
        message: 'Reset link sent successfully!',
      ));
    });
  }

  bool _isValidEmail(String email) {
    final regex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return regex.hasMatch(email);
  }
}
