import Flutter
import UIKit
import GoogleMaps
import UserNotifications

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GMSServices.provideAPIKey("AIzaSyD9UlqOZBQdJIIkfs99hWZstgVhSp_k6fQ")

        GeneratedPluginRegistrant.register(with: self)

        // Set up notification delegate
        UNUserNotificationCenter.current().delegate = self

        // Set up method channel
        if let controller = window?.rootViewController as? FlutterViewController {
            let channel = FlutterMethodChannel(
                name: "com.camelsoft.wanisclient/background",
                binaryMessenger: controller.binaryMessenger
            )

            channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
                if call.method == "wakeAndOpenApp" {
                    if let args = call.arguments as? [String: Any],
                       let title = args["title"] as? String,
                       let message = args["message"] as? String,
                       let rideId = args["rideId"] as? String {
                        self.wakeAndOpenApp(title: title, message: message, rideId: rideId)
                        result("Success")
                    } else {
                        result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid arguments", details: nil))
                    }
                } else {
                    result(FlutterMethodNotImplemented)
                }
            }
        }

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    private func wakeAndOpenApp(title: String, message: String, rideId: String) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = message
        content.sound = UNNotificationSound.defaultCritical
        content.categoryIdentifier = "DRIVER_ARRIVED"
        content.userInfo = ["ride_id": rideId, "driver_arrived": true]
        if #available(iOS 15.0, *) {
            content.interruptionLevel = .timeSensitive
        }
        content.sound = UNNotificationSound.defaultCritical
        let request = UNNotificationRequest(
            identifier: "driver_arrived_\(rideId)",
            content: content,
            trigger: nil
        )

        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("Notification error: \(error)")
            }
        }
    }

    // Handle notification when app is in foreground
    override func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .sound, .badge])
        } else {
            completionHandler([.sound, .badge])
        }
    }

    // Handle notification tap
    override func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo
        if userInfo["driver_arrived"] as? Bool == true {
            // App will open automatically
        }
        completionHandler()
    }
}
