import SwiftUI
import UIKit
import YokanShared

final class ReaderSystemUiViewController: UIViewController {
    private let contentController: UIViewController
    private var readerFullscreen = false
    private var appIsDark = false

    init(contentController: UIViewController) {
        self.contentController = contentController
        super.init(nibName: nil, bundle: nil)
        IosReaderSystemUiBridge.shared.register { [weak self] enabled in
            self?.setReaderFullscreen(enabled.boolValue)
        }
        IosSystemBarThemeBridge.shared.register { [weak self] isDark in
            self?.setAppTheme(isDark.boolValue)
        }
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("ReaderSystemUiViewController must be created programmatically")
    }

    override var prefersStatusBarHidden: Bool {
        readerFullscreen
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        appIsDark ? .lightContent : .darkContent
    }

    override var prefersHomeIndicatorAutoHidden: Bool {
        readerFullscreen
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        addChild(contentController)
        view.addSubview(contentController.view)
        contentController.didMove(toParent: self)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        contentController.view.frame = view.bounds
    }

    deinit {
        IosReaderSystemUiBridge.shared.unregister()
        IosSystemBarThemeBridge.shared.unregister()
    }

    private func setReaderFullscreen(_ enabled: Bool) {
        guard readerFullscreen != enabled else { return }
        readerFullscreen = enabled
        setNeedsStatusBarAppearanceUpdate()
        setNeedsUpdateOfHomeIndicatorAutoHidden()
    }

    private func setAppTheme(_ isDark: Bool) {
        let update = { [weak self] in
            guard let self, self.appIsDark != isDark else { return }
            self.appIsDark = isDark
            self.setNeedsStatusBarAppearanceUpdate()
        }
        if Thread.isMainThread { update() } else { DispatchQueue.main.async(execute: update) }
    }
}

final class AppDelegate: NSObject, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        IosBackgroundTaskRegistration.shared.register()
        return true
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        YokanEmbeddedMihonPause { _ in }
        YokanRuntime.shared.reschedulePeriodicTasks()
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        YokanEmbeddedMihonResume { _ in }
    }

    // Home-screen quick actions (Info.plist UIApplicationShortcutItems) carry a yokan:// route as their type.
    func application(
        _ application: UIApplication,
        configurationForConnecting connectingSceneSession: UISceneSession,
        options: UIScene.ConnectionOptions
    ) -> UISceneConfiguration {
        if let item = options.shortcutItem {
            AppDeepLinks.shared.dispatch(link: item.type)
        }
        let configuration = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
        configuration.delegateClass = QuickActionSceneDelegate.self
        return configuration
    }
}

final class QuickActionSceneDelegate: NSObject, UIWindowSceneDelegate {
    func windowScene(
        _ windowScene: UIWindowScene,
        performActionFor shortcutItem: UIApplicationShortcutItem,
        completionHandler: @escaping (Bool) -> Void
    ) {
        AppDeepLinks.shared.dispatch(link: shortcutItem.type)
        completionHandler(true)
    }
}

struct ComposeRootView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        return ReaderSystemUiViewController(contentController: MainViewControllerKt.MainViewController())
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
    }
}

@main
struct YokanIOSApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate

    var body: some Scene {
        WindowGroup {
            ComposeRootView()
                .ignoresSafeArea()
                .onOpenURL { url in
                    AppDeepLinks.shared.dispatch(link: url.absoluteString)
                }
        }
    }
}
