//
//  YHIdentityTabBar.swift
//  galaxy
//
//  Created by edy on 2024/7/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHIdentityTabBar: UIView {
    
    static let baseTag = 9527
    static let itemWidth = 50.0
    static let itemHeight = 26.0
    static let gap = 10.0
        
    var selectIndex: Int = 0 {
        didSet {
            for (index, item) in self.subviews.enumerated() {
                if item.isKind(of: UIButton.self) {
                    if let itemBtn = item as? UIButton {
                        self.setButton(itemBtn, isSelected: index == self.selectIndex)
                    }
                }
            }
            if 0 <= self.selectIndex, self.selectIndex < self.items.count {
                let selectItem = self.items[self.selectIndex]
                self.selectBlock?(self.selectIndex, selectItem)
            }
        }
    }
    var selectBlock: ((Int, YHHomeLifeCategoryModel) -> Void)?
    var items: [YHHomeLifeCategoryModel] = []
    
    static func tabBarForItems(_ items: [YHHomeLifeCategoryModel]) -> YHIdentityTabBar {
        let bar = YHIdentityTabBar(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 44.0))
        bar.updateItems(items)
        return bar
    }
    
    func updateItems(_ items: [YHHomeLifeCategoryModel]) {
        self.items = items
        self.removeSubviews()
        for (index, item) in items.enumerated() {
            let x = (Self.itemWidth+Self.gap) * Double(index)
            let btn = UIButton(type: .custom)
            btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            btn.setTitle(item.name, for: .normal)
            btn.layer.borderWidth = 1.0
            self.setButton(btn, isSelected: index == 0)
            btn.tag = Self.baseTag + index
            btn.addTarget(self, action: #selector(didTabButtonClicked(_:)), for: .touchUpInside)
            self.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.left.equalTo(x)
                make.centerY.equalToSuperview()
                make.width.equalTo(Self.itemWidth)
                make.height.equalTo(Self.itemHeight)
            }
        }
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    
    func setButton(_ btn: UIButton, isSelected: Bool) {
        let titleColor = isSelected ? UIColor.mainTextColor : UIColor.mainTextColor50
        let borderColor = isSelected ? UIColor.mainTextColor : UIColor.mainTextColor(alpha: 0.18)
        btn.setTitleColor(titleColor, for: .normal)
        btn.layer.borderColor = borderColor.cgColor
    }
    
    @objc func didTabButtonClicked(_ selectBtn: UIButton) {
        let selectIndex = selectBtn.tag-Self.baseTag
        self.selectIndex = selectIndex
    }
}
