//
//  BaseMaskPopDialogController.swift

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

import UIKit

enum EGMaskPopPriority: Int, Comparable {
    case normal = 0
    case level1 = 1
    case level2 = 2
    case level3 = 3
    case level4 = 4
    case required = 10

    // Implement Comparable protocol for priority comparison
    static func < (lhs: EGMaskPopPriority, rhs: EGMaskPopPriority) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }
}

class BaseMaskPopDialogController: CLBaseViewController {
    var bgMaskView = UIView()
    var onlyshowInClass: AnyClass?
    var block: UIView = UIView()
    var closeButton: EPIconTertiaryButton!

    var priority: EGMaskPopPriority = .normal
    var willDismissCalled: (() -> Void)?
    var showActionCalled: (() -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .clear

        view.addSubview(bgMaskView)
        bgMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        bgMaskView.backgroundColor = .c.codr//.white.withAlphaComponent(0.65)
        block = {
            let v = UIView()
            v.layer.cornerRadius = 16
            v.layer.masksToBounds = true
            v.backgroundColor = .c.csbn
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
                make.width.equalTo(UIScreen.width * 0.8)
                make.height.equalTo(360).priority(.low)
            }
            return v
        }()
        
        closeButton = {
            let v = EPIconTertiaryButton(radius: .round, iconSize: .small, iconCode: .delete)
            v.addTarget(self, action: #selector(tapCloseBtn), for: .touchUpInside)
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(8)
                make.size.equalTo(v.bgImageSize())
                make.trailing.equalToSuperview().offset(-8)
            }
            return v
        }()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let navc = navigationController else {
            return
        }
        navc.setNavigationBarHidden(true, animated: animated)
    }

    // MARK: - Class

    public static func getCurrentShowMaskPopVcIfHave() -> BaseMaskPopDialogController? {
        guard let keyVc = UIWindow.getTopViewController() else {
            return nil
        }

        if let tabVc = keyVc.tabBarController {
            for vc in tabVc.children {
                if vc.isKind(of: BaseMaskPopDialogController.self) {
                    return vc as? BaseMaskPopDialogController
                }
            }
        }

        if let navc = keyVc.navigationController {
            for vc in navc.children {
                if vc.isKind(of: BaseMaskPopDialogController.self) {
                    return vc as? BaseMaskPopDialogController
                }
            }
        }

        if let presenting = keyVc.presentingViewController {
            for vc in presenting.children {
                if vc.isKind(of: BaseMaskPopDialogController.self) {
                    return vc as? BaseMaskPopDialogController
                }
            }
        }

        return nil
    }

    // MARK: - Show

    public func show() {
        if let currentShowing = BaseMaskPopDialogController.getCurrentShowMaskPopVcIfHave() {
            if currentShowing.priority < priority { // New dialog has higher priority
                if priority == .required {
                    showForced()
                    return
                } else {
                    DialogPopUpManager.shared.toBeHandleMaskPopControllers.append(currentShowing)
                    DialogPopUpManager.shared.toBeHandleMaskPopControllers.append(self)
                    showForced()
                    return
                }
            } else {
                DialogPopUpManager.shared.toBeHandleMaskPopControllers.append(self)
                print("♻️♻️♻️♻️♻️♻️♻️♻️ \(self) 弹窗被缓存 ♻️♻️♻️♻️♻️♻️♻️♻️")
                return
            }
        }
        
        doLogicToFindShowVcShow()
    }

    public func showForced() {
        if EGNewBaseAlert.existingAlert() {
            EGNewBaseAlert.hideAllAlert()
        }

        if let popVc = BaseMaskPopDialogController.getCurrentShowMaskPopVcIfHave() {
            if DialogPopUpManager.shared.toBeHandleMaskPopControllers.contains(popVc) {
                popVc.dismiss(removePop: false) { [weak self] in
                    self?.doLogicToFindShowVcShow()
                }
            } else {
                popVc.dismiss { [weak self] in
                    self?.doLogicToFindShowVcShow()
                }
            }
        } else {
            doLogicToFindShowVcShow()
        }
    }

    // MARK: - Helper

    private func commonContainerLRPadding() -> Double {
        return UIScreen.main.bounds.size.width * (1 - 0.8) * 0.5
    }

    private func doLogicToFindShowVcShow() {
        guard let keyVc = UIWindow.getTopViewController() else {
            assert(false)
            return
        }

        if let onlyshowInClass = onlyshowInClass, !keyVc.isKind(of: onlyshowInClass) {
            dismiss(completion: nil)
            return
        }
        if let tabbarVc = keyVc.tabBarController {
            subShow(keyVc, tabbar: tabbarVc)
        }

//            let tabbarVc = keyVc?.tabBarController
//            if let presentedVc = keyVc?.presentedViewController, presentedVc is EGUserCenterViewController {
//                let vc = presentedVc as! EGUserCenterViewController
//                vc.dismiss(animated: true) { [weak self] in
//                    self?.subShow(keyVc, tabbar: tabbarVc)
//                }
//            } else {
//                subShow(keyVc, tabbar: tabbarVc)
//            }
    }

    private func subShow(_ keyVc: UIViewController?, tabbar tabbarVc: UITabBarController?) {
        guard let keyVc = keyVc else { return }

        if let tabbarVc = tabbarVc {
            tabbarVc.view.addSubview(view)
            tabbarVc.addChild(self)
        } else if let presentedVc = keyVc.presentedViewController {
            presentedVc.view.addSubview(view)
            presentedVc.addChild(self)
        } else if let navController = keyVc.navigationController {
            navController.view.addSubview(view)
            navController.addChild(self)
            navController.interactivePopGestureRecognizer?.isEnabled = false
        } else {
            keyVc.view.addSubview(view)
            keyVc.addChild(self)
        }

        view.alpha = 0
        UIView.animate(withDuration: 0.35, animations: {
            self.view.alpha = 1
        }, completion: { _ in
            self.viewDidAppear(true)
        })
        view.layer.zPosition = 100
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
            self.view.superview?.bringSubviewToFront(self.view)
        }

        showActionCalled?()
    }

    func dismiss(completion: (() -> Void)? = nil) {
        dismiss(removePop: true, completion: completion)
    }

    func dismiss(removePop: Bool, completion: (() -> Void)? = nil) {
        willDismissCalled?()

        if let navigationController = navigationController {
            navigationController.interactivePopGestureRecognizer?.isEnabled = true
        }
        removeFromParent()

        UIView.animate(withDuration: 0.35, animations: {
            self.view.alpha = 0
        }, completion: { _ in
            self.view.removeFromSuperview()
            self.view.alpha = 1
            self.viewDidDisappear(true)

            if removePop, DialogPopUpManager.shared.toBeHandleMaskPopControllers.contains(self) {
                DialogPopUpManager.shared.toBeHandleMaskPopControllers.removeAll { $0 === self }
            }

            completion?()
            DialogPopUpManager.shared.continueDialogIfHave()
        })
    }

    public func resetPopController() {
        view.removeFromSuperview()
        removeFromParent()
    }
    
    @objc private func tapCloseBtn(){
        dismiss()
    }
}
