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/theme/theme.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/providers/onboarding_provider.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/i18n/translations.g.dart';

final _formStep3Key = GlobalKey<FormState>();

class NotificationsPermissionStep extends ConsumerWidget {
  final String nextRoute;

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final notifRepository = ref.watch(notificationRepositoryProvider);
    final permissionFuture = notifRepository.getPermissionStatus();
    final translations = Translations.of(context).onboarding.notifications;

    return OnboardingBackground(
      child: FutureBuilder<NotificationPermission>(
        future: permissionFuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          }
          return Form(
            key: _formStep3Key,
            child: OnboardingIllustrationScaffold(
              progress: 0.9,
              title: translations.title,
              description: translations.description,
              imageAsset: 'assets/images/onboarding/img2.jpg',
              footerActions: [
                KasyButton(
                  label: translations.continue_button,
                  expand: true,
                  onPressed: () async {
                    try {
                      await ref.onboardingNotifier.setupNotifications();
                    } finally {
                      if (context.mounted) {
                        Navigator.of(context).pushNamed(nextRoute);
                      }
                    }
                  },
                ),
                const SizedBox(height: KasySpacing.smd),
                KasyButton(
                  label: translations.skip_button,
                  variant: KasyButtonVariant.soft,
                  expand: true,
                  onPressed: () {
                    ref
                        .read(analyticsApiProvider)
                        .logEvent('setup_notifications_refused', {});
                    Navigator.of(context).pushNamed(nextRoute);
                  },
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
