import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pweb/controllers/payouts/payout_verification.dart';
import 'package:pweb/pages/payout_verification/page.dart';
import 'package:pweb/utils/error/snackbar.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


Future<bool> runPayoutVerification({
  required BuildContext context,
  required PayoutVerificationController controller,
  required String? contextKey,
}) async {
  final localizations = AppLocalizations.of(context)!;

  controller.setContextKey(contextKey);
  if (controller.isCooldownActiveFor(contextKey)) return false;

  try {
    await controller.requestCode();
  } catch (e) {
    await notifyUserOfError(
      context: context,
      errorSituation: localizations.verificationFailed,
      exception: e,
    );
    return false;
  }

  if (!context.mounted) return false;

  final verified = await Navigator.of(context).push<bool>(
    MaterialPageRoute(
      fullscreenDialog: true,
      builder: (_) => ChangeNotifierProvider.value(
        value: controller,
        child: const PayoutVerificationPage(),
      ),
    ),
  );

  if (verified == true) {
    controller.reset();
  } else {
    controller.resetStatus();
  }

  return verified == true;
}
