import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/data/api/analytics_api.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/features/notifications/providers/models/notification.dart';
import 'package:kasy_kit/features/notifications/repositories/notifications_repository.dart';
import 'package:kasy_kit/features/onboarding/models/user_info.dart';
import 'package:kasy_kit/features/onboarding/providers/onboarding_model.dart';
import 'package:kasy_kit/features/onboarding/repositories/user_infos_repository.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'onboarding_provider.g.dart';

extension OnboardingNotifierExt on WidgetRef {
  OnboardingNotifier get onboardingNotifier =>
      read(onboardingProvider.notifier);

  OnboardingState? get onboardingState$ => watch(onboardingProvider);

  OnboardingNotifier get onboardingState =>
      read(onboardingProvider.notifier);
}

@riverpod
class OnboardingNotifier extends _$OnboardingNotifier {
  @override
  OnboardingState build() {
    return OnboardingState();
  }

  Future<void> onAnsweredQuestion(UserInfoDetail value) async {
    final userId = ref.read(userStateNotifierProvider).user.idOrNull;
    if (userId == null) return; // Guest: no account yet, skip Firestore write
    await ref.read(userInfosRepositoryProvider).save(userId, value);
  }

  Future<void> setupNotifications() async {
    final userStateNotifier = ref.read(userStateNotifierProvider.notifier);
    final notificationsRepository = ref.read(notificationRepositoryProvider);

    try {
      var permission = await notificationsRepository.getPermissionStatus();
      await permission.maybeAsk();

      // The system permission dialog causes the app to go to background.
      // The provider may have been disposed while waiting — bail out if so.
      if (!ref.mounted) return;

      permission = await notificationsRepository.getPermissionStatus();

      if (permission is NotificationPermissionGranted) {
        unawaited(
          ref
              .read(analyticsApiProvider)
              .logEvent('setup_notifications_accepted', {}),
        );
      }

      await userStateNotifier.refresh();
    } catch (_) {
      // Notification setup must not block onboarding progression.
    }
  }

  Future<void> onOnboardingCompleted() async {
    final userStateNotifier = ref.read(userStateNotifierProvider.notifier);

    await userStateNotifier.onOnboarded();
    await userStateNotifier.refresh();
  }

  /// Skip onboarding: mark as onboarded instantly (optimistic) and navigate
  /// to home. Permissions (push + ATT) are requested on the home screen.
  void skipOnboarding() {
    ref.read(userStateNotifierProvider.notifier).onSkippedOnboarding();
  }
}
