import 'package:flutter/foundation.dart';

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

import 'package:pweb/controllers/common/cooldown.dart';
import 'package:pweb/models/state/flow_status.dart';
import 'package:pweb/models/auth/resend/action_result.dart';
import 'package:pweb/models/auth/resend/avaliability.dart';


class SignupConfirmationCardController extends ChangeNotifier {
  SignupConfirmationCardController({
    required AccountProvider accountProvider,
    Duration defaultCooldown = const Duration(seconds: 60),
  }) : _accountProvider = accountProvider,
       _defaultCooldown = defaultCooldown {
    _cooldown = CooldownController(onTick: () => notifyListeners());
  }

  final AccountProvider _accountProvider;
  final Duration _defaultCooldown;
  late final CooldownController _cooldown;
  FlowStatus _resendState = FlowStatus.idle;
  String? _email;

  int get cooldownRemainingSeconds => _cooldown.remainingSeconds;
  ResendAvailability get resendAvailability {
    final email = _email;
    if (email == null || email.isEmpty) {
      return ResendAvailability.missingEmail;
    }
    if (_resendState == FlowStatus.submitting) {
      return ResendAvailability.resending;
    }
    if (_cooldown.isActive) {
      return ResendAvailability.cooldown;
    }
    return ResendAvailability.available;
  }

  void updateEmail(String? email) {
    final trimmed = email?.trim();
    if (_email == trimmed) return;
    _email = trimmed;
    notifyListeners();
  }

  void initialize({String? email}) {
    updateEmail(email);
    startDefaultCooldown();
  }

  void startDefaultCooldown() {
    _startCooldown(_defaultCooldown);
  }

  Future<ResendActionResult> resendVerificationEmail() async {
    switch (resendAvailability) {
      case ResendAvailability.missingEmail:
        return ResendActionResult.missingEmail;
      case ResendAvailability.cooldown:
        return ResendActionResult.cooldown;
      case ResendAvailability.resending:
        return ResendActionResult.inProgress;
      case ResendAvailability.available:
        break;
    }

    _setResendState(FlowStatus.submitting);
    try {
      final email = _email;
      if (email == null || email.isEmpty) {
        _setResendState(FlowStatus.idle);
        return ResendActionResult.missingEmail;
      }
      await _accountProvider.resendVerificationEmail(email);
      _startCooldown(_defaultCooldown);
      return ResendActionResult.sent;
    } finally {
      _setResendState(FlowStatus.idle);
    }
  }

  @override
  void dispose() {
    _cooldown.dispose();
    super.dispose();
  }

  void _startCooldown(Duration duration) {
    _cooldown.start(duration);
  }

  void _setResendState(FlowStatus state) {
    if (_resendState == state) return;
    _resendState = state;
    notifyListeners();
  }
}
