import UIKit
import Capacitor
import CapacitorCommunitySqlite
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Set notification center delegate so notifications show in foreground and rollover is triggered
        UNUserNotificationCenter.current().delegate = self

        // Initialize SQLite
        //let sqlite = SQLite()
        //sqlite.initialize()
        
        // Register SharedImage plugin manually after bridge is ready
        // Try multiple times with increasing delays to ensure bridge is initialized
        var attempts = 0
        let maxAttempts = 5
        
        func tryRegister() {
            attempts += 1
            if registerSharedImagePlugin() {
                print("[AppDelegate] ✅ Plugin registration successful on attempt \(attempts)")
            } else if attempts < maxAttempts {
                DispatchQueue.main.asyncAfter(deadline: .now() + Double(attempts) * 0.5) {
                    tryRegister()
                }
            } else {
                print("[AppDelegate] ⚠️ Failed to register plugin after \(maxAttempts) attempts")
            }
        }
        
        // Start registration attempts
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            tryRegister()
        }
        
        // Override point for customization after application launch.
        return true
    }
    
    @discardableResult
    private func registerSharedImagePlugin() -> Bool {
        guard let window = self.window,
              let bridgeVC = window.rootViewController as? CAPBridgeViewController,
              let bridge = bridgeVC.bridge else {
            return false
        }
        
        // Create plugin instance
        // The @objc(SharedImage) annotation makes it available as "SharedImage" to Objective-C
        // which matches the JavaScript registration name
        let pluginInstance = SharedImagePlugin()
        bridge.registerPluginInstance(pluginInstance)
        print("[AppDelegate] ✅ Registered SharedImagePlugin (exposed as 'SharedImage' via @objc annotation)")
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        
        // Re-set notification delegate when app becomes active (in case Capacitor resets it)
        UNUserNotificationCenter.current().delegate = self

        // Check for shared image from Share Extension when app becomes active
        checkForSharedImageOnActivation()
    }

    // MARK: - UNUserNotificationCenterDelegate

    /// Show notifications when app is in foreground and post DailyNotificationDelivered for rollover.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        if let notificationId = userInfo["notification_id"] as? String,
           let scheduledTime = userInfo["scheduled_time"] as? Int64 {
            NotificationCenter.default.post(
                name: NSNotification.Name("DailyNotificationDelivered"),
                object: nil,
                userInfo: ["notification_id": notificationId, "scheduled_time": scheduledTime]
            )
        }
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .sound, .badge])
        } else {
            completionHandler([.alert, .sound, .badge])
        }
    }

    /// Handle notification tap/interaction.
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
    
    /**
     * Check for shared image when app launches or becomes active
     * This allows the app to detect shared images without requiring a deep link
     * Note: JavaScript will read the shared image via SharedImagePlugin, so we just check the flag
     */
    private func checkForSharedImageOnActivation() {
        // Check if shared photo is ready
        if SharedImageUtility.isSharedPhotoReady() {
            // Clear the flag
            SharedImageUtility.clearSharedPhotoReadyFlag()
                
                // Post notification for JavaScript to handle navigation
            // JavaScript will read the shared image via SharedImagePlugin
                NotificationCenter.default.post(name: NSNotification.Name("SharedPhotoReady"), object: nil)
        }
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
        // Note: Share Extension opens app with timesafari:// (empty path), which is handled by JavaScript
        // via the appUrlOpen listener in main.capacitor.ts
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
    

}
