import 'package:app_links/app_links.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/app.dart';
import 'package:krow/features/auth/domain/bloc/auth_bloc.dart';
import 'package:krow/core/application/routing/routes.gr.dart';

@RoutePage()
class AuthFlowScreen extends StatefulWidget implements AutoRouteWrapper {
  const AuthFlowScreen({super.key});

  @override
  State<AuthFlowScreen> createState() => _AuthFlowScreenState();

  @override
  Widget wrappedRoute(BuildContext context) {
    return BlocProvider(
      create: (_) => AuthBloc(),
      child: this,
    );
  }
}

class _AuthFlowScreenState extends State<AuthFlowScreen> {
  @override
  void initState() {
    super.initState();

    final context = this.context;
    AppLinks().getInitialLink().then(
      (initialLink) {
        if (initialLink == null || !context.mounted) return;

        context
            .read<AuthBloc>()
            .add(SignInWithInitialLink(initialLink: initialLink));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthBloc, AuthState>(
      listener: (context, state) {
        if (state.autentificated) {
          if (state.authType == AuthType.login) {
            appRouter.replace(const SplashRoute());
          } else {
            appRouter.replace(const SignupFlowRoute());
          }
        }
      },
      child: const AutoRouter(),
    );
  }
}
