//
//  SelectAllButton.swift
//  PhoneManager
//
//  Created by edy on 2025/4/21.
//

import Foundation
import UIKit

class SelectAllButton : UIView {
    
    
    var tapCallback : (Bool)->Void = {selected in }
    
    private let imageView = UIImageView()
    private let label = UILabel()
    private var isSelectedValue = false
    
    var isSelected: Bool {
        get {
            return isSelectedValue
        }
        set {
            isSelectedValue = newValue
            updateText()
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        // 设置背景颜色
        backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
        
        // 添加子视图
        addSubview(imageView)
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(selectClick))
        self.addGestureRecognizer(tap)
        
        
        
        addSubview(label)
        
        // 配置图片视图
        imageView.contentMode = .scaleAspectFit
        
        // 配置标签
        label.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        label.textAlignment = .left
        label.textColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
        
        // 使用 SnapKit 进行布局
        imageView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(6)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        label.snp.makeConstraints { make in
            make.leading.equalTo(imageView.snp.trailing).offset(8)
            make.centerY.equalToSuperview()
            make.trailing.lessThanOrEqualToSuperview().offset(-12)
        }
        
        // 初始更新文本
        updateText()
    }
    
    func setImage(_ image: UIImage?) {
        imageView.image = image
    }
    
    
    private func updateText() {
        imageView.image = isSelected ? UIImage(named: "ic_close_similar") : UIImage(named: "ic_check_similar")
        label.textColor = isSelected ? UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1) : UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        label.text = isSelected ? "Deselect all" : "Select All"
        
//        // 强制布局更新以适应新文本
//        UIView.animate(withDuration: 0.1) {
//            self.setNeedsLayout()
//            self.layoutIfNeeded()
//        }
    }
    
    
    @objc func selectClick(){
        self.isUserInteractionEnabled = false
        self.isSelected = !self.isSelected
        tapCallback(self.isSelected)
        DispatchQueue.main.asyncAfter(deadline: .now()+0.01) {
            self.isUserInteractionEnabled = true
        }
    }
    
}
