import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../data/auth_repository.dart';
import '../data/auth_session_store.dart';
import 'login_screen.dart';
import '../../directory/presentation/directory_screen.dart';

class AuthGateScreen extends ConsumerStatefulWidget {
  const AuthGateScreen({super.key});

  static const routePath = '/';

  @override
  ConsumerState<AuthGateScreen> createState() => _AuthGateScreenState();
}

class _AuthGateScreenState extends ConsumerState<AuthGateScreen> {
  var _resolved = false;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<StoredAuthSession?>(
      future: ref.read(authRepositoryProvider).loadSession(),
      builder: (context, snapshot) {
        if (!_resolved && snapshot.connectionState == ConnectionState.done) {
          _resolved = true;
          final router = GoRouter.of(context);
          WidgetsBinding.instance.addPostFrameCallback((_) async {
            final session = snapshot.data;
            if (session == null || session.isExpired) {
              if (session != null) {
                await ref.read(authRepositoryProvider).logout();
              }
              if (mounted) {
                router.go(LoginScreen.routePath);
              }
              return;
            }
            if (mounted) {
              router.go(DirectoryScreen.routePath);
            }
          });
        }

        return const Scaffold(
          body: SafeArea(child: Center(child: CircularProgressIndicator())),
        );
      },
    );
  }
}
