import UIKit
import UserNotifications
import BackgroundTasks
import ComposeApp

@MainActor
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    /// Throttle subscription refreshes to at most once every 5 minutes
    private static var lastSubscriptionRefresh: Date?
    private static let subscriptionRefreshInterval: TimeInterval = 300 // 5 minutes

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        // Set notification delegate
        UNUserNotificationCenter.current().delegate = self

        // Register notification categories for actionable notifications
        NotificationCategories.registerCategories()

        // Register background tasks for overnight data refresh
        BackgroundTaskManager.shared.registerBackgroundTasks()

        // Request notification permission
        Task {
            await PushNotificationManager.shared.requestNotificationPermission()
        }

        // Clear badge when app launches
        PushNotificationManager.shared.clearBadge()

        // Initialize StoreKit and check for existing subscriptions
        // This ensures we have the user's subscription status ready before they interact
        Task {
            _ = StoreKitManager.shared
            #if DEBUG
            print("StoreKit initialized at app launch")
            #endif
        }

        return true
    }

    // MARK: - App Lifecycle

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Clear badge when app becomes active
        PushNotificationManager.shared.clearBadge()

        // Refresh StoreKit subscription status when app comes to foreground (throttled to every 5 min)
        // This ensures we have the latest subscription state if it changed while app was in background
        let now = Date()
        if let lastRefresh = Self.lastSubscriptionRefresh,
           now.timeIntervalSince(lastRefresh) < Self.subscriptionRefreshInterval {
            // Skip — refreshed recently
        } else {
            Self.lastSubscriptionRefresh = now
            Task {
                await StoreKitManager.shared.refreshSubscriptionStatus()
            }
        }
    }

    // MARK: - Remote Notifications

    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        PushNotificationManager.shared.didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
    }

    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        PushNotificationManager.shared.didFailToRegisterForRemoteNotifications(withError: error)
    }

    // MARK: - UNUserNotificationCenterDelegate

    // Called when notification is received while app is in foreground
    nonisolated func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        #if DEBUG
        let userInfo = notification.request.content.userInfo
        let payloadKeys = Array(userInfo.keys).map { String(describing: $0) }.sorted()
        print("Notification received in foreground. Keys: \(payloadKeys)")
        #endif

        // Passive mode in foreground: present banner/sound, but do not
        // mutate read state or trigger navigation automatically.
        completionHandler([.banner, .sound, .badge])
    }

    // Called when user taps on notification or selects an action
    nonisolated func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo
        let actionIdentifier = response.actionIdentifier

        #if DEBUG
        print("User interacted with notification - Action: \(actionIdentifier)")
        let payloadKeys = Array(userInfo.keys).map { String(describing: $0) }.sorted()
        print("   Payload keys: \(payloadKeys)")
        #endif

        Task { @MainActor in
            // Handle action buttons or default tap
            if actionIdentifier == UNNotificationDefaultActionIdentifier {
                // User tapped the notification body - navigate to task
                PushNotificationManager.shared.handleNotificationTap(userInfo: userInfo)
            } else if actionIdentifier == UNNotificationDismissActionIdentifier {
                #if DEBUG
                print("Notification dismissed")
                #endif
            } else {
                // User selected an action button
                PushNotificationManager.shared.handleNotificationAction(
                    actionIdentifier: actionIdentifier,
                    userInfo: userInfo
                )
            }

            completionHandler()
        }
    }
}
