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/features/sign_up/presentation/screens/account_created_screen.dart';
import 'package:auth/src/features/sign_up/presentation/screens/secret_code_screen.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';

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(context);
    final isLastStep = state.currentIndex >= steps.length - 1;

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

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

    if (!ok) return;
  }

  @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(context);
    final index = state.currentIndex.clamp(0, steps.length - 1);
    final step = steps[index];

    if (state.showSecretCode) {
      return SecretCodeScreen(navigationContract: navigationContract);
    }

    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),
    );
  }
}
