import 'package:auth/src/features/login/presentation/widgets/two_factor_bottom_sheet.dart';
import 'package:auth/src/features/sign_up/presentation/account_created_screen.dart';
import 'package:auth/src/features/sign_up/presentation/sign_up_steps.dart';
import 'package:auth/src/features/sign_up/presentation/state/sign_up_view_model.dart';
import 'package:auth/src/widgets/layouts/sign_up_layout.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:navigation/navigation.dart';
import 'package:sf_localizations/sf_localizations.dart';

class SignupScreen extends ConsumerWidget {
  final NavigationContract navigationContract;

  const SignupScreen({super.key, required this.navigationContract});

  Future<void> _onNextPressed(BuildContext context, WidgetRef ref) async {
    FocusManager.instance.primaryFocus?.unfocus();

    final vm = ref.read(signUpViewModelProvider.notifier);
    final state = ref.read(signUpViewModelProvider);

    final steps = signUpSteps();
    final isLastStep = state.currentIndex >= steps.length - 1;

    if (!isLastStep) {
      vm.next();
      return;
    }

    final isSignUp = await vm.signUp();
    if (!context.mounted) return;

    if (!isSignUp) return;

    final verified = await _openTwoFactorSignUpBottomSheet(context, ref);
    if (!context.mounted) return;

    if (verified == true) {
      vm.showAccountCreated();
    }
  }

  Future<bool?> _openTwoFactorSignUpBottomSheet(
    BuildContext context,
    WidgetRef ref,
  ) async {
    final token = ref.read(signUpViewModelProvider).token;
    if (token.trim().isEmpty) return false;

    return showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      isDismissible: false,
      enableDrag: false,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Consumer(
          builder: (context, ref, _) {
            final theme = ref.watch(themePortProvider);
            final vm = ref.read(signUpViewModelProvider.notifier);

            final otpErrorKey = ref.watch(
              signUpViewModelProvider.select((s) => s.otpError),
            );
            final isOtpLoading = ref.watch(
              signUpViewModelProvider.select((s) => s.isOtpLoading),
            );
            final otpCode = ref.watch(
              signUpViewModelProvider.select((s) => s.otpCode),
            );

            final otpErrorText = otpErrorKey.isEmpty
                ? ''
                : context.translate(otpErrorKey);

            Future<void> onVerify() async {
              FocusManager.instance.primaryFocus?.unfocus();

              final ok = await vm.verifyTwoFACodeSignUp(token: token);
              if (!context.mounted) return;

              if (ok) Navigator.of(context).pop(true);
            }

            return TwoFactorBottomSheetView(
              theme: theme,
              title: context.translate(I18n.twoFactorTitle),
              subtitle: context.translate(I18n.twoFactorSubtitle),
              verifyText: context.translate(I18n.twoFactorVerify),
              closeText: context.translate(I18n.close),
              isOtpLoading: isOtpLoading,
              otpCode: otpCode,
              otpErrorText: otpErrorText,
              onChanged: vm.setOtpCode,
              onVerify: onVerify,
              onClose: () => Navigator.of(context).pop(false),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = ref.watch(themePortProvider);
    final vm = ref.read(signUpViewModelProvider.notifier);
    final state = ref.watch(signUpViewModelProvider);

    final steps = signUpSteps();
    final index = state.currentIndex.clamp(0, steps.length - 1);
    final step = steps[index];

    if (state.showAccountCreated) {
      return AccountCreatedScreen(navigationContract: navigationContract);
    }
    return SignUpLayout(
      theme: theme,
      supertitle: step.supertitle,
      title: step.title,
      subtitle: step.subtitle ?? '',
      currentStep: index + 1,
      numSteps: steps.length,
      body: step.bodyBuilder(context, ref),
      errorMessage: state.errorMessage,
      onBackPressed: state.currentIndex == 0
          ? navigationContract.goBack
          : vm.back,
      onNextPressed: () => _onNextPressed(context, ref),
    );
  }
}
