import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/config/features.dart';
import 'package:kasy_kit/core/data/models/user.dart';
import 'package:kasy_kit/core/guards/guard.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';

class UserInfosGuard extends ConsumerWidget {
  final Widget child;
  final String fallbackRoute;

  const UserInfosGuard({
    super.key,
    required this.child,
    required this.fallbackRoute,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(userStateNotifierProvider);
    if (authState.user.isLoading) {
      return Material(
        color: context.colors.background,
        child: const Center(
          child: CircularProgressIndicator.adaptive(),
        ),
      );
    }

    // Web: skip onboarding but require sign-in (or explicit guest choice).
    // The /signin page's "Continue without account" button calls onOnboarded()
    // which marks isOnboarded=true locally, allowing the guard to pass.
    if (kIsWeb && withWeb) {
      return Guard(
        canActivate: Future.value(
          authState.user.idOrNull != null || authState.user.isOnboarded,
        ),
        fallbackRoute: '/signin',
        child: child,
      );
    }

    // Native: all users (including guests with no ID) go through onboarding.
    // Guests are never forced to /signin here; individual features that
    // require authentication redirect to /signin on their own.
    // Authenticated users skip onboarding: they already committed to an account
    // (e.g. returning user signing back in after the anonymous session was
    // discarded by `credential-already-in-use`).
    return Guard(
      canActivate: Future.value(
        !withOnboarding ||
            authState.user.isOnboarded ||
            authState.user is AuthenticatedUserData,
      ),
      fallbackRoute: fallbackRoute,
      child: child,
    );
  }
}
