//
//  AppRouter.swift

//
//  Created by Leon on 2025/7/12.
//

import Foundation

@objcMembers class AppRouter: NSObject {
    static let shared = AppRouter()
    var isBlockBackRootVc: Bool = false
    
    static func goBackRootController(jumpIndex: TabBarItemIndex = .home, block: (() -> Void)? = nil) {
        guard let window = UIWindow.applicationKey else {
            assert(false)
            block?()
            return
        }
        guard let rootVC = window.rootViewController else {
            assert(false)
            block?()
            return
        }

        // 取消拦截
//        if AppRouter.shared.isBlockBackRootVc {
//            block?()
//            return
//        }

        AppRouter.shared.isBlockBackRootVc = true

        var presentedController: UIViewController?
        if rootVC is UITabBarController {
            if let vc = (rootVC as? TabBarController)?.selectedViewController {
                presentedController = vc
            }
        }
        var presentedControllers = [UIViewController]()
        while presentedController?.presentedViewController != nil {
            if let vc = rootVC.presentedViewController {
                presentedControllers.append(vc)
                presentedController = vc
            }
        }
        if presentedControllers.count > 0 {
            dismissControllers(presentedControllers: presentedControllers, index: presentedControllers.count - 1) {
                popToRootController(from: rootVC) {
                    guard let vc = rootVC as? TabBarController else {
                        AppRouter.shared.isBlockBackRootVc = false
                        return
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                        vc.setSelected(index: jumpIndex)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
                            block?()
                            AppRouter.shared.isBlockBackRootVc = false
                        }
                    }
                }
            }
        } else {
            popToRootController(from: presentedController ?? rootVC, animated: false) {
                guard let vc = rootVC as? TabBarController else {
                    AppRouter.shared.isBlockBackRootVc = false
                    return
                }
//                DispatchQueue.main.asyncAfter(deadline: .now() + 0) { // 0.25
                    vc.setSelected(index: jumpIndex)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
                        block?()
                        AppRouter.shared.isBlockBackRootVc = false
                    }
//                }
            }
        }
    }

    static func dismissControllers(presentedControllers: [UIViewController], index: Int, completion: @escaping (() -> Void)) {
        if index < 0 {
            completion()
        } else {
            guard let vc = presentedControllers[safe: index] else { return }
            vc.dismiss(animated: false) {
                dismissControllers(presentedControllers: presentedControllers, index: index - 1, completion: completion)
            }
        }
    }

    static func popToRootController(from vc: UIViewController, animated: Bool? = true, completion: @escaping (() -> Void)) {
        if vc is UINavigationController {
            if let navc = vc as? UINavigationController {
                navc.popToRootViewController(animated: animated ?? true)
                completion()
            }
        }
        if let navc = vc.navigationController {
            navc.popToRootViewController(animated: animated ?? true)
            completion()
        }
    }
}

extension AppRouter{
    static func goCreateEditAIRole(aiId: Int? = nil, aiEditInfo: AIUserModel? = nil) {
        if AppDictManager.shared.aiDict == nil{
            Hud.showIndicator()
            AppDictManager.shared.loadAIDict { ok in
                Hud.hideIndicator()
                if ok{
                    AppRouter.goCreateEditAIRole(aiId: aiId)
                }
            }
            return
        }
        
        if let id = aiId, id > 0{ // 编辑
            if aiEditInfo == nil{ // 请求编辑用信息
                Hud.showIndicator()
                AIRoleProvider.request(.aiInfoMineGet(id: id), modelType: AIUserModel.self) { result in
                    Hud.hideIndicator()
                    switch result {
                    case .success(let success):
                        if let editInfo = success{
                            AppRouter.goCreateEditAIRole(aiId: id, aiEditInfo: editInfo)
                        }
                    case .failure:
                        break
                    }
                }
                return
            }
        }
        
        
        let vc = RoleClassificationSelectController()
        vc.viewModel.editAIInfo = aiEditInfo
        let navc = CLNavigationController(rootViewController: vc)
        UIWindow.getTopViewController()?.present(navc, animated: true)
    }
    
    static func goAIRoleHome(aiId: Int?){
        guard let id = aiId else {return}
        let vc = RoleHomePagerController()
        vc.aiId = id
        UIWindow.getTopNavigationController()?.pushViewController(vc, animated: true)
    }
    
    // 首次创建, alert是否创建相册
    static func alertCreateAlbumsToRoleHome(aiId: Int?){
        
        let alert = Alert(title: "Create Album", text: "Go to your personal homepage to create albums for your characters, attract interlocutors and increase revenue.")
        let action1 = AlertAction(title: "Go", actionStyle: .confirm) {
            AppRouter.goAIRoleHome(aiId: aiId)
        }
        let action2 = AlertAction(title: "Not now", actionStyle: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.show()
    }
    

}
