import 'package:flutter/material.dart';

import 'package:pshared/provider/account.dart';
import 'package:pshared/provider/email_verification.dart';

import 'package:pweb/models/state/flow_status.dart';


class AccountVerificationController extends ChangeNotifier {
  AccountVerificationController({
    required AccountProvider accountProvider,
    required EmailVerificationProvider verificationProvider,
  }) : _accountProvider = accountProvider,
       _verificationProvider = verificationProvider {
    _verificationProvider.addListener(_onVerificationChanged);
  }

  final AccountProvider _accountProvider;
  final EmailVerificationProvider _verificationProvider;

  FlowStatus _resendStatus = FlowStatus.idle;
  String? _verificationToken;

  bool get isLoading => _verificationProvider.isLoading;
  bool get isSuccess => _verificationProvider.isSuccess;
  Exception? get error => _verificationProvider.error;
  bool get canResend => _verificationProvider.canResendVerification;
  bool get isResending => _resendStatus == FlowStatus.resending;
  bool get isAlreadyVerified => _verificationProvider.isTokenAlreadyUsed;

  void startVerification(String token) {
    final trimmed = token.trim();
    if (trimmed.isEmpty || trimmed == _verificationToken) return;
    _verificationToken = trimmed;
    _verificationProvider.verify(trimmed);
  }

  Future<void> resendVerificationEmail(String email) async {
    final trimmed = email.trim();
    if (trimmed.isEmpty || isResending) return;
    _setResendStatus(FlowStatus.resending);
    try {
      await _accountProvider.resendVerificationEmail(trimmed);
      _setResendStatus(FlowStatus.idle);
    } catch (_) {
      _setResendStatus(FlowStatus.error);
      rethrow;
    }
  }

  void _onVerificationChanged() {
    notifyListeners();
  }

  void _setResendStatus(FlowStatus status) {
    _resendStatus = status;
    notifyListeners();
  }

  @override
  void dispose() {
    _verificationProvider.removeListener(_onVerificationChanged);
    super.dispose();
  }
}
