//
//  MenuButton.swift
//  MpAccDemo
//
//  Created by Robin on 2023/10/14.
//

import UIKit

class MenuButton: UIButton, ConfigItemViewProtocol {
    
    static func newItem() -> ConfigItemViewProtocol {
        let btn = MenuButton(type: .system)
        btn.addConstraint(btn.widthAnchor.constraint(greaterThanOrEqualToConstant: 80))
        return btn
    }
    var currentItem: MpItem!
    var itemList: [MpItem]!
    var saveBlock: ((MpItem) -> Void)?
    var changedBlock: ((MpItem) -> Void)?
    
    func currentItemDidChanged() {
        if #unavailable(iOS 15.0) {
            self.setTitle(self.currentItem.title, for: .normal)
        }
    }
    
    func itemListChanged() {
        guard itemList.count > 0 else {
            return
        }
        if #available(iOS 15.0, *) {
            let actions = itemList.map { item in
                let action = UIAction(title: item.title) { [weak self] _ in
                    self?.updateCurrentItem(item)
                }
                if item.on {
                    action.state = .on
                }
                return action
            }
            if actions.contains(where: { $0.state == .on }) == false {
                actions.first?.state = .on
            }
            self.menu = UIMenu(children: actions)
            self.showsMenuAsPrimaryAction = true
            self.changesSelectionAsPrimaryAction = true
        } else {
            self.addTarget(MenuButton.self, action: #selector(MenuButton.tapAction), for: .touchUpInside)
        }
        self.setImage(UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(scale: .small)), for: .normal)
        self.semanticContentAttribute = .forceRightToLeft
        self.titleLabel?.font = .boldSystemFont(ofSize: 20)
    }
    
    @objc private static func tapAction(_ sender: MenuButton) {
        guard let itemList = sender.itemList  else { return }
        let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        itemList.forEach { item in
            let action = UIAlertAction(title: item.title, style: .default) { action in
                sender.updateCurrentItem(item)
            }
            sheet.addAction(action)
        }
        
        sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        App.topPresentPage?.present(sheet, animated: true)
    }
    
    func addChangeBlock(block:@escaping ((MpItem) -> Void)) -> MenuButton {
        self.changedBlock = block
        return self
    }
}
