import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dreamxapplication/models/package.dart';
import 'package:dreamxapplication/providers/firebase_provider.dart';
import 'package:dreamxapplication/providers/package_provider.dart';
import 'package:dreamxapplication/views/package/ads_view.dart';
import 'package:dreamxapplication/views/payments/subscription_screen.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  String userName = 'User';
  int points = 0;
  Map<int, PackageProgress> packageProgress = {};
  int _selectedTab = 0;
  Map<int, Duration> timers = {};
  Timer? _timer;
  String? imageUrl;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadInitialData();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _loadInitialData() async {
    final packageProvider =
        Provider.of<PackageProvider>(context, listen: false);
    final firebaseManager =
        Provider.of<FirebaseManagerProvider>(context, listen: false);
    try {
      await packageProvider.fetchPackages();
      if (firebaseManager.currentUser != null &&
          packageProvider.packages.isNotEmpty) {
        await firebaseManager.initializePackageProgress(
            firebaseManager.currentUser!.uid, packageProvider.packages);
      }
      await _loadUserData();
      await _loadPackageData();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error loading initial data: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _loadUserData() async {
    final firebaseManager =
        Provider.of<FirebaseManagerProvider>(context, listen: false);
    final user = firebaseManager.currentUser;
    if (user != null) {
      try {
        final userData = await firebaseManager.getUser(user.uid);
        if (userData != null) {
          setState(() {
            userName = userData.fullName ?? 'User';
            points = (userData.points as num?)?.toInt() ?? 0;
            imageUrl = userData.profileImageUrl?.toString();
          });
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Error loading user data')),
          );
        }
      }
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('User not logged in')),
        );
      }
    }
  }

  Future<void> _loadPackageData() async {
    final firebaseManager =
        Provider.of<FirebaseManagerProvider>(context, listen: false);
    final packageProvider =
        Provider.of<PackageProvider>(context, listen: false);
    final user = firebaseManager.currentUser;
    final packages = packageProvider.packages;
    final progress = <int, PackageProgress>{};

    if (user != null) {
      try {
        for (var pkg in packages) {
          // Fetch existing progress from Firestore
          var pkgProgress =
              await firebaseManager.getPackageProgress(user.uid, pkg.id);
          if (pkgProgress != null) {
            // Check if reset is needed based on nextRefresh
            final now = DateTime.now();
            final nextRefresh = pkgProgress.nextRefresh?.toDate();
            if (nextRefresh != null && now.isAfter(nextRefresh)) {
              await firebaseManager.resetPackageProgress(
                  user.uid, pkg.id, pkg.refreshSchedule);
              // Reload progress after reset
              pkgProgress =
                  await firebaseManager.getPackageProgress(user.uid, pkg.id);
              progress[pkg.id] = pkgProgress ??
                  PackageProgress(
                    packageId: pkg.id,
                    adsWatched: 0,
                    isSubscribed: false,
                    isCompleted: false,
                    pointsEarned: 0,
                    lastRefreshed: Timestamp.fromDate(now),
                    nextRefresh:
                        _calculateNextRefresh(now, pkg.refreshSchedule),
                  );
            } else {
              // Use existing progress if no reset is needed
              progress[pkg.id] = pkgProgress;
            }
          } else {
            // Initialize new progress only if none exists
            await firebaseManager.initializePackageProgress(user.uid, [pkg]);
            pkgProgress =
                await firebaseManager.getPackageProgress(user.uid, pkg.id);
            progress[pkg.id] = pkgProgress ??
                PackageProgress(
                  packageId: pkg.id,
                  adsWatched: 0,
                  isSubscribed: false,
                  isCompleted: false,
                  pointsEarned: 0,
                  lastRefreshed: Timestamp.now(),
                  nextRefresh: _calculateNextRefresh(
                      DateTime.now(), pkg.refreshSchedule),
                );
          }

          // New: If nextRefresh is still null after fetch/init (edge case), recalculate it
          if (progress[pkg.id]!.nextRefresh == null) {
            final recalculatedNext =
                _calculateNextRefresh(DateTime.now(), pkg.refreshSchedule);
            if (recalculatedNext != null) {
              await FirebaseFirestore.instance
                  .collection(
                      'users') // Assuming _usersCollection from provider
                  .doc(user.uid)
                  .collection('packageProgress')
                  .doc(pkg.id.toString())
                  .update({'nextRefresh': recalculatedNext});
              progress[pkg.id]!.nextRefresh = recalculatedNext;
              if (kDebugMode) {
                print(
                    'Recalculated nextRefresh for package ${pkg.id}: $recalculatedNext');
              }
            }
          }

          // Always calculate the current timer duration after loading or resetting
          timers[pkg.id] =
              _calculateTimerDuration(progress[pkg.id]!.nextRefresh);
          if (kDebugMode) {
            print(
                'Package ${pkg.id}: adsWatched = ${progress[pkg.id]!.adsWatched}, totalAds = ${pkg.totalAds}, timer = ${_formatTimer(timers[pkg.id]!)}, schedule = ${pkg.refreshSchedule}, nextRefresh = ${progress[pkg.id]!.nextRefresh}');
          }

          // New: Check subscription status and handle approval if needed
          final status = await firebaseManager.getSubscriptionStatus(
            user.uid,
            pkg.id,
            pkg.name,
            progress[pkg.id]!.lastRefreshed,
          );
          if (status == 'approved' && !progress[pkg.id]!.isSubscribed) {
            await firebaseManager.handleSubscriptionApproval(user.uid, pkg.id);
            // Reload progress after handling approval
            final updatedProgressAfterApproval =
                await firebaseManager.getPackageProgress(user.uid, pkg.id);
            progress[pkg.id] = updatedProgressAfterApproval ??
                progress[pkg.id]!; // Fallback to current if fetch fails
            if (kDebugMode) {
              print('Handled approval for package ${pkg.id}: Updated progress');
            }
          }
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Error loading package progress: $e')),
          );
        }
      }
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('User not logged in')),
        );
      }
    }

    if (mounted) {
      setState(() {
        packageProgress = progress;
        _checkPackageAvailability(packages);
      });
      _startTimers();
    }
  }

  Duration _calculateTimerDuration(Timestamp? nextRefresh) {
    if (nextRefresh == null) {
      return Duration.zero; // No refresh scheduled; show 0 time
    }
    final now = DateTime.now();
    final refreshTime = nextRefresh.toDate();
    final remaining = refreshTime.difference(now);
    return remaining.isNegative ? Duration.zero : remaining;
  }

  void _startTimers() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      if (!mounted) {
        timer.cancel();
        return;
      }
      final firebaseManager =
          Provider.of<FirebaseManagerProvider>(context, listen: false);
      final packageProvider =
          Provider.of<PackageProvider>(context, listen: false);
      final user = firebaseManager.currentUser;
      bool needsUpdate = false;

      for (var pkg in packageProvider.packages) {
        if ((pkg.hasAds || pkg.id == 8) && timers.containsKey(pkg.id)) {
          final currentTimer = timers[pkg.id]!;
          if (currentTimer.inSeconds > 0) {
            timers[pkg.id] = currentTimer - const Duration(seconds: 1);
            needsUpdate =
                true; // Trigger UI update every second for active timers
            if (kDebugMode) {
              print(
                  'Package ${pkg.id}: timer = ${_formatTimer(timers[pkg.id]!)}');
            }
          } else if (currentTimer.inSeconds <= 0 && user != null) {
            // Only reset if timer has exactly reached or passed zero
            try {
              await firebaseManager.resetPackageProgress(
                  user.uid, pkg.id, pkg.refreshSchedule);
              await Future.delayed(const Duration(milliseconds: 500));

              final updatedProgress =
                  await firebaseManager.getPackageProgress(user.uid, pkg.id);
              if (kDebugMode) print('Reset triggered for package ${pkg.id}');
              if (mounted) {
                setState(() {
                  packageProgress[pkg.id] = updatedProgress ??
                      PackageProgress(
                        packageId: pkg.id,
                        adsWatched: 0,
                        isSubscribed: false,
                        isCompleted: false,
                        pointsEarned: 0, // Reset pointsEarned to 0 on refresh
                        lastRefreshed: Timestamp.now(),
                        nextRefresh: _calculateNextRefresh(
                            DateTime.now(), pkg.refreshSchedule),
                      );
                  timers[pkg.id] =
                      _calculateTimerDuration(updatedProgress?.nextRefresh);
                  needsUpdate = true;
                  if (kDebugMode) {
                    print(
                        'Package ${pkg.id} reset: adsWatched = 0, timer restarted = ${_formatTimer(timers[pkg.id]!)}');
                  }
                });
              }
            } catch (e) {
              if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                      content: Text(
                          'Error resetting package ${pkg.id} progress: $e')),
                );
              }
            }
          }
        }
      }

      if (needsUpdate && mounted) {
        setState(() {
          _checkPackageAvailability(packageProvider.packages);
        });
      }
    });
  }

  Timestamp? _calculateNextRefresh(DateTime now, String refreshSchedule) {
    DateTime? nextDate;
    switch (refreshSchedule) {
      case 'daily':
        nextDate = now.add(const Duration(days: 1));
        break;
      case 'tuesday_friday':
        final today = now.weekday;
        if (today == DateTime.tuesday) {
          nextDate = now.add(const Duration(days: 3)); // Next Friday
        } else if (today == DateTime.friday) {
          nextDate = now.add(const Duration(days: 4)); // Next Tuesday
        } else {
          final daysUntilTuesday = (DateTime.tuesday - today) % 7;
          nextDate = now.add(
              Duration(days: daysUntilTuesday == 0 ? 7 : daysUntilTuesday));
        }
        break;
      case 'sunday':
        final daysUntilSunday = (DateTime.sunday - now.weekday) % 7;
        nextDate =
            now.add(Duration(days: daysUntilSunday == 0 ? 7 : daysUntilSunday));
        break;
      case '15_days':
        nextDate = now.add(const Duration(days: 15));
        break;
      case 'monthly':
        nextDate = DateTime(now.year, now.month + 1, now.day);
        break;
      case 'weekly':
        final daysUntilMonday = (DateTime.monday - now.weekday) % 7;
        nextDate =
            now.add(Duration(days: daysUntilMonday == 0 ? 7 : daysUntilMonday));
        break;
      default:
        return null;
    }
    // Ensure nextDate is set to a future time; adjust if calculated to past or current
    if (nextDate != null && nextDate.isBefore(now)) {
      // If somehow calculated to past, add the period again (edge case prevention)
      switch (refreshSchedule) {
        case 'daily':
          nextDate = nextDate.add(const Duration(days: 1));
          break;
        case '15_days':
          nextDate = nextDate.add(const Duration(days: 15));
          break;
        case 'monthly':
          nextDate = DateTime(nextDate.year, nextDate.month + 1, nextDate.day);
          break;
        // For others, it's already handled by modulo logic
      }
    }
    return nextDate != null ? Timestamp.fromDate(nextDate) : null;
  }

  void _checkPackageAvailability(List<Package> packages) {
    final completedPackages = packages.where((pkg) {
      final progress = packageProgress[pkg.id];
      return progress != null && progress.isCompleted && pkg.id != 5;
    }).toList();
    final allRequiredCompleted = [1, 2, 3, 4, 6, 7]
        .every((id) => completedPackages.any((pkg) => pkg.id == id));
    Provider.of<PackageProvider>(context, listen: false)
        .updatePackageEnableStatus(8, allRequiredCompleted);
  }

  String _formatTimer(Duration duration) {
    final days = duration.inDays;
    final hours = duration.inHours % 24;
    final minutes = duration.inMinutes % 60;
    final seconds = duration.inSeconds % 60;
    return '${days}d ${hours}h ${minutes}m ${seconds}s';
  }

  void _subscribeToPackage(int packageId) {
    final firebaseManager =
        Provider.of<FirebaseManagerProvider>(context, listen: false);
    final packageProvider =
        Provider.of<PackageProvider>(context, listen: false);
    try {
      final package =
          packageProvider.packages.firstWhere((pkg) => pkg.id == packageId);
      final user = firebaseManager.currentUser;
      if (user != null) {
        firebaseManager.subscribeToPackage(
            user.uid, packageId, package.subscriptionPoints);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text(
                  'Subscribed! +${package.subscriptionPoints} points awarded.')),
        );
        _loadPackageData();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('User not logged in')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error subscribing to package: $e')),
      );
    }
  }

  bool _isSubscribed(int packageId) {
    final progress = packageProgress[packageId];
    return progress?.isSubscribed ?? false;
  }

  Future<void> _handleAdNavigation(
      FirebaseManagerProvider firebaseManager, Package pkg) async {
    final currentCount = packageProgress[pkg.id]?.adsWatched ?? 0;
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AdsViewScreen(
          packageId: pkg.id.toString(),
          package: pkg,
          addCounter: currentCount,
          totalAds: pkg.totalAds,
        ),
      ),
    );

    if (result != null && mounted) {
      final user = firebaseManager.currentUser;
      if (user != null) {
        try {
          final userData = await firebaseManager.getUser(user.uid);
          final updatedProgress =
              await firebaseManager.getPackageProgress(user.uid, pkg.id);
          setState(() {
            if (userData != null) {
              points = (userData.points as num?)?.toInt() ?? points;
            }
            packageProgress[pkg.id] = updatedProgress ??
                PackageProgress(
                  packageId: pkg.id,
                  adsWatched: result['adsWatched'] ?? currentCount,
                  isSubscribed: false,
                  isCompleted: result['isCompleted'] ?? false,
                  pointsEarned: 0,
                  lastRefreshed: Timestamp.now(),
                  nextRefresh: _calculateNextRefresh(
                      DateTime.now(), pkg.refreshSchedule),
                );
            if (kDebugMode) {
              print(
                  'Updated package ${pkg.id}: adsWatched = ${packageProgress[pkg.id]!.adsWatched}');
            }
          });
        } catch (e) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Error updating progress: $e')),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('User not logged in')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(
                color: Color(0xffFF5722),
              ),
            )
          : Padding(
              padding: const EdgeInsets.fromLTRB(16, 50, 16, 16),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            ClipOval(
                              child: imageUrl != null
                                  ? Image.network(
                                      imageUrl!,
                                      width: 40,
                                      height: 40,
                                      fit: BoxFit.cover,
                                      errorBuilder:
                                          (context, error, stackTrace) =>
                                              const Icon(Icons.person,
                                                  size: 40,
                                                  color: Colors.white),
                                    )
                                  : Image.asset(
                                      'assets/images/main_screen_avatar.png',
                                      width: 40,
                                      height: 40,
                                      fit: BoxFit.cover,
                                      errorBuilder:
                                          (context, error, stackTrace) =>
                                              const Icon(Icons.person,
                                                  size: 40,
                                                  color: Colors.white),
                                    ),
                            ),
                            const SizedBox(width: 8),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'Welcome!!',
                                  style: TextStyle(
                                      color: Color(0xFFCCCCCC), fontSize: 12),
                                ),
                                Text(
                                  userName,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        GestureDetector(
                          onTap: () => Navigator.pushNamed(context, '/winners'),
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                                vertical: 8, horizontal: 12),
                            decoration: BoxDecoration(
                              color: Colors.grey[900],
                              borderRadius: BorderRadius.circular(25),
                            ),
                            child: Row(
                              children: [
                                const Icon(Icons.star,
                                    color: Color(0xFFFFD700), size: 20),
                                const SizedBox(width: 4),
                                Text(
                                  '$points',
                                  style: const TextStyle(
                                      color: Colors.white, fontSize: 14),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),
                    const Text(
                      'Available Packages',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      'Watch videos and complete tasks to earn points - Earn up to 200 points per action!',
                      style: TextStyle(color: Color(0xFFCCCCCC), fontSize: 13),
                    ),
                    const SizedBox(height: 16),
                    Consumer<PackageProvider>(
                      builder: (context, packageProvider, child) {
                        final packages = packageProvider.packages;
                        if (packages.isEmpty) {
                          return const Center(
                              child: Text('No packages available',
                                  style: TextStyle(color: Colors.white)));
                        }
                        return Consumer<FirebaseManagerProvider>(
                          builder: (context, firebaseManager, child) {
                            return Column(
                              children: packages.map((pkg) {
                                if (!pkg.isEnabled)
                                  return const SizedBox.shrink();

                                final progress = packageProgress[pkg.id] ??
                                    PackageProgress(
                                        packageId: pkg.id, adsWatched: 0);
                                final currentCount = progress.adsWatched;
                                if (kDebugMode) {
                                  print(
                                      'Rendering package ${pkg.id}: adsWatched = $currentCount, totalAds = ${pkg.totalAds}');
                                }

                                return Card(
                                  color: pkg.color != null
                                      ? Color(int.parse(
                                          pkg.color.replaceFirst('#', '0xff')))
                                      : Colors.grey,
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(16)),
                                  margin: const EdgeInsets.only(bottom: 16),
                                  child: Column(
                                    children: [
                                      Container(
                                        width: double.infinity,
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 4, horizontal: 16),
                                        color: pkg.color != null
                                            ? Color(int.parse(pkg.color
                                                    .replaceFirst('#', '0xff')))
                                                .withOpacity(0.5)
                                            : Colors.grey.withOpacity(0.5),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            Image.asset(
                                              'assets/images/timer_ic.png',
                                              width: 16,
                                              height: 16,
                                              errorBuilder: (context, error,
                                                      stackTrace) =>
                                                  const Icon(Icons.timer,
                                                      size: 16,
                                                      color: Colors.white),
                                            ),
                                            const SizedBox(width: 8),
                                            Text(
                                              _formatTimer(timers[pkg.id] ??
                                                  Duration.zero),
                                              style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 12,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.all(16),
                                        child: Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Image.asset(
                                              'assets/images/package${pkg.id}.png',
                                              width: 60,
                                              height: 60,
                                              errorBuilder: (context, error,
                                                      stackTrace) =>
                                                  const Icon(Icons.image,
                                                      size: 60,
                                                      color: Colors.white),
                                            ),
                                            const SizedBox(width: 16),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    pkg.name,
                                                    style: const TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 18,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                    ),
                                                  ),
                                                  const SizedBox(height: 4),
                                                  Text(
                                                    pkg.description,
                                                    style: const TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 14),
                                                  ),
                                                  if (pkg.hasAds ||
                                                      pkg.id == 7) ...[
                                                    const SizedBox(height: 24),
                                                    Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        Text(
                                                          pkg.id == 6
                                                              ? 'Tasks Completed'
                                                              : pkg.id == 8
                                                                  ? 'VIP Actions Completed'
                                                                  : 'Ads Watched',
                                                          style:
                                                              const TextStyle(
                                                                  color: Colors
                                                                      .white,
                                                                  fontSize: 14),
                                                        ),
                                                        Text(
                                                          '$currentCount/${pkg.totalAds}',
                                                          style:
                                                              const TextStyle(
                                                                  color: Colors
                                                                      .white,
                                                                  fontSize: 14),
                                                        ),
                                                      ],
                                                    ),
                                                    const SizedBox(height: 8),
                                                    LinearProgressIndicator(
                                                      value: pkg.totalAds == 0
                                                          ? 0
                                                          : currentCount /
                                                              pkg.totalAds,
                                                      backgroundColor:
                                                          Colors.grey[700],
                                                      valueColor:
                                                          const AlwaysStoppedAnimation(
                                                              Colors.white),
                                                      minHeight: 8,
                                                    ),
                                                  ],
                                                  const SizedBox(height: 16),
                                                  // Updated: Wrap buttons in FutureBuilder for status check
                                                  FutureBuilder<String?>(
                                                    future: firebaseManager
                                                        .getSubscriptionStatus(
                                                      firebaseManager
                                                              .currentUser
                                                              ?.uid ??
                                                          '',
                                                      pkg.id,
                                                      pkg.name,
                                                      packageProgress[pkg.id]
                                                          ?.lastRefreshed,
                                                    ),
                                                    builder:
                                                        (context, snapshot) {
                                                      final status = snapshot
                                                              .data ??
                                                          'none'; // Fallback to 'none' on error/null

                                                      // Helper to get button background color (grey if pending/approved, white otherwise)
                                                      Color getButtonColor() {
                                                        return (status ==
                                                                    'pending' ||
                                                                status ==
                                                                    'approved')
                                                            ? Colors.grey
                                                            : const Color(
                                                                0xFFFFFFFF);
                                                      }

                                                      return Row(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .end,
                                                        children: [
                                                          if (pkg.id == 1 &&
                                                              pkg.hasAds)
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style: const TextStyle(
                                                                    color: Colors
                                                                        .black,
                                                                    fontSize:
                                                                        14),
                                                              ),
                                                            ),
                                                          if (pkg.id == 2 &&
                                                              pkg.hasAds) ...[
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style: const TextStyle(
                                                                    color: Colors
                                                                        .black,
                                                                    fontSize:
                                                                        14),
                                                              ),
                                                            ),
                                                            const SizedBox(
                                                                width: 8),
                                                            if (pkg
                                                                .hasSubscription)
                                                              ElevatedButton(
                                                                style: ElevatedButton
                                                                    .styleFrom(
                                                                  backgroundColor:
                                                                      getButtonColor(),
                                                                ),
                                                                onPressed: (status ==
                                                                            'pending' ||
                                                                        status ==
                                                                            'approved')
                                                                    ? () {
                                                                        ScaffoldMessenger.of(context)
                                                                            .showSnackBar(SnackBar(
                                                                          content: Text(status == 'pending'
                                                                              ? 'You already applied. Wait for approval.'
                                                                              : 'Subscription approved. Wait for refresh to access again.'),
                                                                        ));
                                                                      }
                                                                    : () {
                                                                        if (kDebugMode)
                                                                          print(
                                                                              '${pkg.price}');
                                                                        Navigator
                                                                            .push(
                                                                          context,
                                                                          MaterialPageRoute(
                                                                            builder: (context) =>
                                                                                SubscriptionScreen(
                                                                              packageId: pkg.id,
                                                                              packageName: pkg.name,
                                                                              packageDescription: pkg.description,
                                                                              packagePrice: pkg.price,
                                                                            ),
                                                                          ),
                                                                        );
                                                                      },
                                                                child: Text(
                                                                  status ==
                                                                          'pending'
                                                                      ? 'Pending'
                                                                      : (status ==
                                                                              'approved'
                                                                          ? 'Subscribed'
                                                                          : 'Subscribe'),
                                                                  style: const TextStyle(
                                                                      color: Colors
                                                                          .black,
                                                                      fontSize:
                                                                          14),
                                                                ),
                                                              ),
                                                          ],
                                                          if (pkg.id == 3 &&
                                                              pkg.hasAds) ...[
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style: const TextStyle(
                                                                    color: Colors
                                                                        .black,
                                                                    fontSize:
                                                                        14),
                                                              ),
                                                            ),
                                                            const SizedBox(
                                                                width: 8),
                                                            if (pkg
                                                                .hasSubscription)
                                                              ElevatedButton(
                                                                style: ElevatedButton
                                                                    .styleFrom(
                                                                  backgroundColor:
                                                                      getButtonColor(),
                                                                ),
                                                                onPressed: (status ==
                                                                            'pending' ||
                                                                        status ==
                                                                            'approved')
                                                                    ? () {
                                                                        ScaffoldMessenger.of(context)
                                                                            .showSnackBar(SnackBar(
                                                                          content: Text(status == 'pending'
                                                                              ? 'You already applied. Wait for approval.'
                                                                              : 'Subscription approved. Wait for refresh to access again.'),
                                                                        ));
                                                                      }
                                                                    : () {
                                                                        if (kDebugMode)
                                                                          print(
                                                                              '${pkg.price}');
                                                                        Navigator
                                                                            .push(
                                                                          context,
                                                                          MaterialPageRoute(
                                                                            builder: (context) =>
                                                                                SubscriptionScreen(
                                                                              packageId: pkg.id,
                                                                              packageName: pkg.name,
                                                                              packageDescription: pkg.description,
                                                                              packagePrice: pkg.price,
                                                                            ),
                                                                          ),
                                                                        );
                                                                      },
                                                                child: Text(
                                                                  status ==
                                                                          'pending'
                                                                      ? 'Pending'
                                                                      : (status ==
                                                                              'approved'
                                                                          ? 'Subscribed'
                                                                          : 'Subscribe'),
                                                                  style: const TextStyle(
                                                                      color: Colors
                                                                          .black,
                                                                      fontSize:
                                                                          14),
                                                                ),
                                                              ),
                                                          ],
                                                          if (pkg.id == 4 &&
                                                              pkg.hasAds) ...[
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style:
                                                                    const TextStyle(
                                                                  color: Colors
                                                                      .black,
                                                                  fontSize: 14,
                                                                ),
                                                              ),
                                                            ),
                                                            const SizedBox(
                                                                width: 8),
                                                            if (pkg
                                                                .hasSubscription)
                                                              ElevatedButton(
                                                                style: ElevatedButton
                                                                    .styleFrom(
                                                                  backgroundColor:
                                                                      getButtonColor(),
                                                                ),
                                                                onPressed: (status ==
                                                                            'pending' ||
                                                                        status ==
                                                                            'approved')
                                                                    ? () {
                                                                        ScaffoldMessenger.of(context)
                                                                            .showSnackBar(SnackBar(
                                                                          content: Text(status == 'pending'
                                                                              ? 'You already applied. Wait for approval.'
                                                                              : 'Subscription approved. Wait for refresh to access again.'),
                                                                        ));
                                                                      }
                                                                    : () {
                                                                        if (kDebugMode)
                                                                          print(
                                                                              '${pkg.price}');
                                                                        Navigator
                                                                            .push(
                                                                          context,
                                                                          MaterialPageRoute(
                                                                            builder: (context) =>
                                                                                SubscriptionScreen(
                                                                              packageId: pkg.id,
                                                                              packageName: pkg.name,
                                                                              packageDescription: pkg.description,
                                                                              packagePrice: pkg.price,
                                                                            ),
                                                                          ),
                                                                        );
                                                                      },
                                                                child: Text(
                                                                  status ==
                                                                          'pending'
                                                                      ? 'Pending'
                                                                      : (status ==
                                                                              'approved'
                                                                          ? 'Subscribed'
                                                                          : 'Subscribe'),
                                                                  style: const TextStyle(
                                                                      color: Colors
                                                                          .black,
                                                                      fontSize:
                                                                          14),
                                                                ),
                                                              ),
                                                          ],
                                                          if (pkg.id == 6 &&
                                                              pkg.hasAds)
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style: const TextStyle(
                                                                    color: Colors
                                                                        .black,
                                                                    fontSize:
                                                                        14),
                                                              ),
                                                            ),
                                                          if (pkg.id == 7)
                                                            FutureBuilder<bool>(
                                                              future: FirebaseFirestore
                                                                  .instance
                                                                  .collection(
                                                                      'rewardsRegistrations')
                                                                  .where('uid',
                                                                      isEqualTo: Provider.of<FirebaseManagerProvider>(
                                                                              context,
                                                                              listen:
                                                                                  false)
                                                                          .currentUser
                                                                          ?.uid)
                                                                  .where(
                                                                      'packageId',
                                                                      isEqualTo:
                                                                          pkg
                                                                              .id)
                                                                  .get()
                                                                  .then((snapshot) =>
                                                                      snapshot
                                                                          .docs
                                                                          .isNotEmpty),
                                                              builder: (context,
                                                                  snapshot) {
                                                                final isRegistered =
                                                                    snapshot.data ??
                                                                        false;
                                                                return ElevatedButton(
                                                                  style: ElevatedButton
                                                                      .styleFrom(
                                                                    backgroundColor:
                                                                        const Color(
                                                                            0xFFFFFFFF),
                                                                  ),
                                                                  onPressed:
                                                                      () async {
                                                                    final firebaseManager = Provider.of<
                                                                            FirebaseManagerProvider>(
                                                                        context,
                                                                        listen:
                                                                            false);
                                                                    final user =
                                                                        firebaseManager
                                                                            .currentUser;
                                                                    if (user !=
                                                                        null) {
                                                                      try {
                                                                        if (isRegistered) {
                                                                          ScaffoldMessenger.of(context)
                                                                              .showSnackBar(
                                                                            const SnackBar(content: Text('You are already registered')),
                                                                          );
                                                                        } else {
                                                                          Navigator
                                                                              .pushNamed(
                                                                            context,
                                                                            '/register_for_rewards_screen',
                                                                            arguments:
                                                                                pkg.id.toString(),
                                                                          );
                                                                        }
                                                                      } catch (e) {
                                                                        if (kDebugMode)
                                                                          print(
                                                                              'Error checking registration: $e');
                                                                        ScaffoldMessenger.of(context)
                                                                            .showSnackBar(
                                                                          SnackBar(
                                                                              content: Text('Error checking registration: $e')),
                                                                        );
                                                                      }
                                                                    } else {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                        const SnackBar(
                                                                            content:
                                                                                Text('User not logged in')),
                                                                      );
                                                                    }
                                                                  },
                                                                  child: Text(
                                                                    isRegistered
                                                                        ? 'Registered'
                                                                        : 'Register',
                                                                    style: const TextStyle(
                                                                        color: Colors
                                                                            .black,
                                                                        fontSize:
                                                                            14),
                                                                  ),
                                                                );
                                                              },
                                                            ),
                                                          if (pkg.id == 8 &&
                                                              pkg.hasAds) ...[
                                                            ElevatedButton(
                                                              style:
                                                                  ElevatedButton
                                                                      .styleFrom(
                                                                backgroundColor:
                                                                    getButtonColor(),
                                                              ),
                                                              onPressed: (status ==
                                                                          'pending' ||
                                                                      status ==
                                                                          'approved' ||
                                                                      currentCount >=
                                                                          pkg
                                                                              .totalAds)
                                                                  ? () {
                                                                      ScaffoldMessenger.of(
                                                                              context)
                                                                          .showSnackBar(
                                                                              SnackBar(
                                                                        content: Text(status ==
                                                                                'pending'
                                                                            ? 'You applied for the subscription.'
                                                                            : 'Subscription approved. Wait for refresh to access again.'),
                                                                      ));
                                                                    }
                                                                  : () => _handleAdNavigation(
                                                                      firebaseManager,
                                                                      pkg),
                                                              child: Text(
                                                                (status == 'approved' &&
                                                                        pkg.hasAds)
                                                                    ? 'Pkg Bought'
                                                                    : 'Watch Ads',
                                                                style: const TextStyle(
                                                                    color: Colors
                                                                        .black,
                                                                    fontSize:
                                                                        14),
                                                              ),
                                                            ),
                                                            const SizedBox(
                                                                width: 8),
                                                            if (pkg
                                                                .hasSubscription)
                                                              ElevatedButton(
                                                                style: ElevatedButton
                                                                    .styleFrom(
                                                                  backgroundColor:
                                                                      getButtonColor(),
                                                                ),
                                                                onPressed: (status ==
                                                                            'pending' ||
                                                                        status ==
                                                                            'approved')
                                                                    ? () {
                                                                        ScaffoldMessenger.of(context)
                                                                            .showSnackBar(SnackBar(
                                                                          content: Text(status == 'pending'
                                                                              ? 'You already applied. Wait for approval.'
                                                                              : 'Subscription approved. Wait for refresh to access again.'),
                                                                        ));
                                                                      }
                                                                    : () {
                                                                        if (kDebugMode)
                                                                          print(
                                                                              '${pkg.price}');
                                                                        Navigator
                                                                            .push(
                                                                          context,
                                                                          MaterialPageRoute(
                                                                            builder: (context) =>
                                                                                SubscriptionScreen(
                                                                              packageId: pkg.id,
                                                                              packageName: pkg.name,
                                                                              packageDescription: pkg.description,
                                                                              packagePrice: pkg.price,
                                                                            ),
                                                                          ),
                                                                        );
                                                                      },
                                                                child: Text(
                                                                  status ==
                                                                          'pending'
                                                                      ? 'Pending'
                                                                      : (status ==
                                                                              'approved'
                                                                          ? 'Subscribed'
                                                                          : 'Subscribe'),
                                                                  style: const TextStyle(
                                                                      color: Colors
                                                                          .black,
                                                                      fontSize:
                                                                          14),
                                                                ),
                                                              ),
                                                          ],
                                                        ],
                                                      );
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }).toList(),
                            );
                          },
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}
This is the code. You just need to add the subscribe button at package 6, just like the other packages have, for those with ads.  Only generate that part of the code, but first, read it thoroughly.