//
//  KMCompressSettingViewController.swift
//  PDF Reader Pro
//
//  Created by lizhe on 2024/11/15.
//

import Cocoa
import KMComponentLibrary

typealias KMCompressSettingViewControllerCancelAction = (_ controller: KMCompressSettingViewController ) -> Void
typealias KMCompressSettingViewControllerDoneAction = (_ controller: KMCompressSettingViewController ) -> Void
typealias KMCompressSettingViewControllerModelChangeAction = (_ controller: KMCompressSettingViewController, _ model: KMCompressSettingModel) -> Void

class KMCompressSettingViewController: KMBaseViewController {
    @IBOutlet weak var doneButton: ComponentButton!
    @IBOutlet weak var cancelButton: ComponentButton!
    @IBOutlet weak var settingView: KMCompressSettingTableView!
    @IBOutlet weak var titleLabel: NSTextField!
    
    private var toastViews: [NSView] = [] // 用于管理多个 alertView
    
    var cancelAction: KMCompressSettingViewControllerCancelAction?
    var doneAction: KMCompressSettingViewControllerDoneAction?
    var modelChangeAction: KMCompressSettingViewControllerModelChangeAction?
    
    var model: KMCompressSettingModel = KMCompressSettingModel(modelsType: .standard) {
        didSet {
            self.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        // 将按钮设置为第一响应者
//        if let window = view.window {
//            
//            window.makeFirstResponder(doneButton.nextResponder)
//            window.defaultButtonCell = doneButton.cell as? NSButtonCell
//            
//            window.contentMinSize = CGSizeMake(624, 513)
//            window.contentMaxSize = CGSizeMake(624, 513)
//        }
        
        self.updateUI()
        
        self.settingView.valueChangeAction = { [unowned self] view, tModel in
            if tModel.fontUnembed == false {
                if KMCompressSettingManager.shared.fetchFontCount() == 1 {
                    self.showAlert("Unembed any font may result in incomplete display of text")
                }
            }
            
            let count = tModel.objectOptions.numberOfSetOptions() + tModel.userDataOptions.numberOfSetOptions() + tModel.otherDataOptions.numberOfSetOptions()
            if count < 7 {
                if KMCompressSettingManager.shared.fetchLimitAlert() == 1 {
                    self.showAlert("Less than 7 items selected; compression quality may be affected")
                }
            }
            
            guard let callBack = modelChangeAction else { return }
            
            callBack(self, tModel)
        }
    }
    
    func updateUI() {
        doneButton.properties = ComponentButtonProperty(type: .primary, size: .xs, buttonText: KMLocalizedString("Compress"), keepPressState: false)
        doneButton.setTarget(self, action: #selector(doneButtonAction(_:)))
        doneButton.reloadData()
        
        cancelButton.properties = ComponentButtonProperty(type: .default_tertiary, size: .xs, buttonText: KMLocalizedString("Cancel"), keepPressState: false)
        cancelButton.setTarget(self, action: #selector(cancelButtonAction(_:)))
        cancelButton.reloadData()
        
        titleLabel.stringValue = KMLocalizedString("Advanced Compress Settings", comment: "")
        titleLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/1")
        //ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
    }
    
    func reloadData() {
        self.settingView.model = model
    }

    func showAlert(_ string: String) {
        let centerYOffset = CGRectGetHeight(self.view.frame) / 2 + CGFloat((46 + 12) * (toastViews.count - 1)) // 每个 Toast 间隔 30px
        
        let alertView = ComponentMessage()
        alertView.properties = ComponentMessageProperty(messageType: .warning, title: KMLocalizedString(string))
        alertView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - alertView.properties.propertyInfo.viewWidth)/2,
                                     CGRectGetHeight(self.view.frame) - alertView.properties.propertyInfo.viewHeight - centerYOffset,
                                     alertView.properties.propertyInfo.viewWidth,
                                     alertView.properties.propertyInfo.viewHeight)
        alertView.reloadData()
        self.view.addSubview(alertView)
        
        // 添加到管理数组
        toastViews.append(alertView)
        
        // 自动移除视图
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.removeAlert(alertView)
        }
    }

    private func removeAlert(_ alertView: NSView) {
        // 淡出动画
        NSAnimationContext.runAnimationGroup({ context in
            context.duration = 0.3
            alertView.animator().alphaValue = 0
        }, completionHandler: {
            // 从视图和数组中移除
            alertView.removeFromSuperview()
            if let index = self.toastViews.firstIndex(of: alertView) {
                self.toastViews.remove(at: index)
            }
            // 重新布局其他 Toast
            self.rearrangeToasts()
        })
    }

    private func rearrangeToasts() {
        for (index, toastView) in toastViews.enumerated() {
            let newYOffset = CGFloat(-46 * index)
            if let constraint = toastView.constraints.first(where: { $0.firstAttribute == .centerY }) {
                constraint.constant = newYOffset
            }
        }
    }
}

extension KMCompressSettingViewController {
    @objc func cancelButtonAction(_ sender: Any) {
        guard let callBack = cancelAction else { return }
        
        callBack(self)
    }
    
    @objc func doneButtonAction(_ sender: Any) {
        guard let callBack = doneAction else { return }
        
        callBack(self)
    }
}