import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/data/api/analytics_api.dart';
import 'package:kasy_kit/core/data/api/tracking_api.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/features/onboarding/ui/widgets/onboarding_background.dart';
import 'package:kasy_kit/features/onboarding/ui/widgets/onboarding_illustration_scaffold.dart';
import 'package:kasy_kit/features/subscription/repositories/subscription_repository.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:permission_handler/permission_handler.dart';

/// ATT Permission Step
/// ATT is only available on iOS
/// This is the consent screen for iOS 14+ that asks the user to allow the app to access the ATT framework
/// In a few words you need this to get the IDFA (Identifier for Advertisers) which is used for tracking purposes
/// So you can create better facebook ads, google ads, etc...
class AttPermissionStep extends ConsumerWidget {
  final String nextRoute;

  const AttPermissionStep({
    super.key,
    required this.nextRoute,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final translations = Translations.of(context).onboarding.att;

    return OnboardingBackground(
      child: OnboardingIllustrationScaffold(
        progress: 0.9,
        title: translations.title,
        description: translations.description,
        imageAsset: 'assets/images/onboarding/img3.jpg',
        footerActions: [
          KasyButton(
            label: translations.continue_button,
            expand: true,
            onPressed: () async {
              final Map<Permission, PermissionStatus> permission = await [
                Permission.appTrackingTransparency,
              ].request();
              final isGranted =
                  permission.values.first == PermissionStatus.granted;
              ref.read(analyticsApiProvider).logEvent('att_request', {
                'granted': isGranted,
              });
              final userId =
                  ref.read(userStateNotifierProvider).user.idOrNull;
              if (userId != null) {
                ref
                    .read(subscriptionRepositoryProvider)
                    .initUser(userId)
                    .ignore();
                ref.read(facebookEventApiProvider).initUser(userId).ignore();
              }
              if (!context.mounted) return;
              Navigator.of(context).pushNamed(nextRoute);
            },
          ),
        ],
      ),
    );
  }
}
