import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pweb/pages/2fa/error_message.dart';
import 'package:pweb/pages/2fa/input.dart';
import 'package:pweb/pages/2fa/prompt.dart';
import 'package:pweb/pages/2fa/resend.dart';
import 'package:pweb/providers/two_factor.dart';

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


class TwoFactorCodePage extends StatelessWidget {
  final VoidCallback onVerificationSuccess;

  const TwoFactorCodePage({
    super.key,
    required this.onVerificationSuccess,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<TwoFactorProvider>(
      builder: (context, provider, child) {
        final email = provider.pendingLogin?.target ?? '';
        if (provider.verificationSuccess) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            onVerificationSuccess();
          });
        }

        return Scaffold(
          appBar: AppBar(title: const Text('')),
          body: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TwoFactorPromptText(email: email),
                const SizedBox(height: 32),
                TwoFactorCodeInput(
                  onCompleted: (code) => provider.submitCode(code),
                ),
                const SizedBox(height: 24),
                if (provider.isSubmitting)
                  const Center(child: CircularProgressIndicator())
                else
                  ResendCodeButton(
                    onPressed: provider.resendCode,
                    isCooldownActive: provider.isCooldownActive,
                    isResending: provider.isResending,
                    cooldownRemainingSeconds: provider.cooldownRemainingSeconds,
                  ),
                if (provider.hasError) ...[
                  const SizedBox(height: 12),
                  ErrorMessage(error: AppLocalizations.of(context)!.twoFactorError),
                ],
              ],
            ),
          ),
        );
      },
    );
  }
}
