//
//  KeyboardFunctionPopView.swift
//  AiKeyboard
//
//  Created by Destiny on 2025/4/23.
//

import UIKit

class KeyboardFunctionPopView: UIView {
    
    var selectClosure: ((KeyboardType) -> Void)?
    
    var buttons = [UIButton]()
    
    var selectType: KeyboardType? {
        didSet {
            self.updateUI()
        }
    }
    
    lazy var contentView: UIView = {
       
        let view = UIView()
        view.isHidden = true
        view.backgroundColor = .white
        view.layer.cornerRadius = 16
        return view
    }()
    
    lazy var selectFuncView: UIView = {
       
        let view = UIView()
        
        view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(closeButtonTapped))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var selectFuncLabel: UILabel = {
       
        let label = UILabel()
        label.text = "帮聊"
        label.font = .boldSystemFont(ofSize: 12)
        label.textColor = .hexStringColor(hexString: "#000000", alpha: 0.8)
        return label
    }()
    
    lazy var arrowIcon: UIImageView = {
       
        let icon = UIImageView()
        icon.image = UIImage(named: "icon_arrow_up")
        return icon
    }()
    
    lazy var funcHelpBtn: UIButton = {
       
        let btn = UIButton()
        btn.tag = 0
        btn.isSelected = true
        btn.setBackgroundImage(UIImage(named: "keyboard_func_select_bg"), for: .selected)
        btn.setTitle("帮聊", for: .normal)
        btn.setTitleColor(.hexStringColor(hexString: "#000000", alpha: 0.8), for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
        btn.addTarget(self, action: #selector(functionBtnTapped(_:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var funcTeachBtn: UIButton = {
       
        let btn = UIButton()
        btn.tag = 1
        btn.setBackgroundImage(UIImage(named: "keyboard_func_select_bg"), for: .selected)
        btn.setTitle("教你说", for: .normal)
        btn.setTitleColor(.hexStringColor(hexString: "#000000", alpha: 0.8), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.addTarget(self, action: #selector(functionBtnTapped(_:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var funcPrologueBtn: UIButton = {
       
        let btn = UIButton()
        btn.tag = 2
        btn.setBackgroundImage(UIImage(named: "keyboard_func_select_bg"), for: .selected)
        btn.setTitle("开场白", for: .normal)
        btn.setTitleColor(.hexStringColor(hexString: "#000000", alpha: 0.8), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.addTarget(self, action: #selector(functionBtnTapped(_:)), for: .touchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
        setupTapGesture()
        
        buttons = [funcHelpBtn, funcTeachBtn, funcPrologueBtn]
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class func show(view: UIView, selectType: KeyboardType, selectClosure: @escaping (KeyboardType) -> Void) {
        
        let window = KeyboardFunctionPopView(frame: CGRect(x: 0, y: 0, width: KeyboardConst.kb_kScreenW, height: KeyboardConst.kb_kScreenH))
        window.selectClosure = selectClosure
        window.selectType = selectType
        view.addSubview(window)
        window.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.95, initialSpringVelocity: 0.05) {
            window.contentView.isHidden = false
        }
    }
}

extension KeyboardFunctionPopView {
    
    @objc func closeButtonTapped() {
        self.removeFromSuperview()
    }
    
    @objc func functionBtnTapped(_ sender: UIButton) {
        
        for button in buttons {
            button.isSelected = false
        }
        sender.isSelected = true
        self.selectClosure?(KeyboardType(rawValue: sender.tag) ?? .teach)
        self.closeButtonTapped()
    }
}

extension KeyboardFunctionPopView: UIGestureRecognizerDelegate {
    
    // 添加点击手势识别器
    private func setupTapGesture() {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleBackgroundTap(_:)))
        tapGesture.delegate = self
        self.addGestureRecognizer(tapGesture)
    }
    
    // MARK: - Actions
    @objc private func handleBackgroundTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: self)
        if !contentView.frame.contains(location) {
            self.closeButtonTapped()
        }
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        // 确保点击事件不是发生在containerView上
        let location = touch.location(in: self)
        return !contentView.frame.contains(location)
    }
}

extension KeyboardFunctionPopView {
    
    func updateUI() {
        
        switch self.selectType {
        case .help:
            self.selectFuncLabel.text = "帮聊"
            break
        case .teach:
            self.selectFuncLabel.text = "教你说"
            break
        case .prologue:
            self.selectFuncLabel.text = "开场白"
            break
        default:
            break
        }
        
        for button in buttons {
            if button.tag == self.selectType?.rawValue ?? 0 {
                button.isSelected = true
                button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
            } else {
                button.isSelected = false
                button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            }
        }
    }
    
    func setUI() {
        
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 85, height: 162))
            make.left.equalTo(55)
            make.top.equalTo(17)
        }
        
        contentView.addSubview(selectFuncView)
        selectFuncView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(32)
        }
        
        selectFuncView.addSubview(selectFuncLabel)
        selectFuncLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.centerY.equalToSuperview()
        }
        
        selectFuncView.addSubview(arrowIcon)
        arrowIcon.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 18, height: 18))
            make.centerY.equalToSuperview()
            make.right.equalTo(-5)
        }
        
        contentView.addSubview(funcHelpBtn)
        funcHelpBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 81, height: 32))
            make.left.equalTo(2)
            make.right.equalTo(-2)
            make.top.equalTo(selectFuncView.snp.bottom).offset(9)
        }
        
        contentView.addSubview(funcTeachBtn)
        funcTeachBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 81, height: 32))
            make.left.equalTo(2)
            make.right.equalTo(-2)
            make.top.equalTo(funcHelpBtn.snp.bottom).offset(8)
        }
        
        contentView.addSubview(funcPrologueBtn)
        funcPrologueBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 81, height: 32))
            make.left.equalTo(2)
            make.right.equalTo(-2)
            make.top.equalTo(funcTeachBtn.snp.bottom).offset(8)
        }
    }
}
