import 'dart:async';

import 'package:flutter/foundation.dart';

import 'package:pshared/models/auth/probe_result.dart';
import 'package:pshared/provider/account.dart';


class SignupConfirmationProvider extends ChangeNotifier {
  SignupConfirmationProvider({
    required AccountProvider accountProvider,
    Duration pollInterval = const Duration(seconds: 10),
  }) : _accountProvider = accountProvider,
       _pollInterval = pollInterval;

  final AccountProvider _accountProvider;
  final Duration _pollInterval;

  Timer? _pollTimer;
  bool _isChecking = false;
  bool _isAuthorized = false;

  String? _email;
  String? _password;
  String? _locale;

  bool get isAuthorized => _isAuthorized;
  bool get isChecking => _isChecking;

  void startPolling({
    required String email,
    required String password,
    required String locale,
  }) {
    final trimmedEmail = email.trim();
    final trimmedPassword = password.trim();
    final trimmedLocale = locale.trim();
    if (trimmedEmail.isEmpty || trimmedPassword.isEmpty || trimmedLocale.isEmpty) {
      return;
    }

    _email = trimmedEmail;
    _password = trimmedPassword;
    _locale = trimmedLocale;

    _pollTimer?.cancel();
    _pollTimer = Timer.periodic(_pollInterval, (_) => _probeAuthorization());
    _probeAuthorization();
  }

  void stopPolling() {
    _pollTimer?.cancel();
    _pollTimer = null;
  }

  @override
  void dispose() {
    _pollTimer?.cancel();
    super.dispose();
  }

  Future<void> _probeAuthorization() async {
    if (_isChecking || _isAuthorized) return;
    final email = _email;
    final password = _password;
    final locale = _locale;
    if (email == null || password == null || locale == null) return;

    _setChecking(true);
    try {
      final result = await _accountProvider.probeAuthorization(
        email: email,
        password: password,
        locale: locale,
      );
      if (result == AuthProbeResult.authorized) {
        _isAuthorized = true;
        stopPolling();
        notifyListeners();
      }
    } finally {
      _setChecking(false);
    }
  }

  void _setChecking(bool value) {
    if (_isChecking == value) return;
    _isChecking = value;
    notifyListeners();
  }
}
