//
//  HorizontalScrollTagsView.swift

//
//  Created by Leon on 2025/9/28.
//

import UIKit
import SnapKit

/*
控件： 横向可滚动的tag选择器，可多选，可不选
要求： 使用EPChipFilterButton
可能用scrollView +stackView的方式？
 
外部可能约束 HorizontalScrollTagsView的高度和宽度。EPChipFilterButton竖直方向上居中，高度默认控件EPChipFilterButton内部自行约束高度。
 
 选择变更，触发string，和index索引的变更回调
 可设置选择tag区域 左右inset
 */

/*
 Example:
 
 let tagsView = HorizontalScrollTagsView()
 tagsView.setTags(["标签1", "标签2", "标签3"])
 tagsView.selectionCallback = { selectedTags, selectedIndices in
     print("选中的标签: \(selectedTags)")
     print("选中的索引: \(selectedIndices)")
 }
 
 */

/// 标签选择回调
typealias TagSelectionCallback = ([String], [Int]) -> Void

class HorizontalScrollTagsView: UIView {
    
    // MARK: - Properties
    
    /// 滚动视图
    private var scrollView: UIScrollView!
    
    /// 标签容器
    private var stackView: UIStackView!
    
    /// 标签按钮数组
    private var tagButtons: [EPRoleTagsFilterButton] = []
    
    /// 标签数据源
    private var tags: [String] = []
    
    /// 选中的标签索引
    private var selectedIndices: Set<Int> = []
    
    /// 选择回调
    var selectionCallback: TagSelectionCallback?
    
    /// 标签间距
    var tagSpacing: CGFloat = 12 {
        didSet {
            stackView.spacing = tagSpacing
        }
    }
    
    /// 左右内边距
    var horizontalInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 24) {
        didSet {
            updateStackViewConstraints()
        }
    }
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    
    private func setupViews() {
        // 设置滚动视图
        scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.contentInsetAdjustmentBehavior = .never
        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 设置堆栈视图
        stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fill
        stackView.spacing = tagSpacing
        scrollView.addSubview(stackView)
        updateStackViewConstraints()
    }
    
    private func updateStackViewConstraints() {
        stackView.snp.remakeConstraints { make in
            make.edges.equalToSuperview().inset(horizontalInsets)
            make.height.equalToSuperview()
        }
    }
    
    // MARK: - Public Methods
    
    /// 设置标签数据
    /// - Parameter tags: 标签文本数组
    func setTags(_ tags: [String]) {
        self.tags = tags
        createTagButtons()
    }
    
    /// 设置选中的标签索引
    /// - Parameter indices: 选中的索引数组
    func setSelectedIndices(_ indices: [Int]) {
        selectedIndices.removeAll()
        for index in indices {
            if index >= 0 && index < tagButtons.count {
                selectedIndices.insert(index)
                tagButtons[index].isSelected = true
            }
        }
    }
    
    /// 获取选中的标签文本
    /// - Returns: 选中的标签文本数组
    func getSelectedTags() -> [String] {
        return selectedIndices.compactMap { index in
            index < tags.count ? tags[index] : nil
        }
    }
    
    /// 获取选中的标签索引
    /// - Returns: 选中的标签索引数组
    func getSelectedIndices() -> [Int] {
        return Array(selectedIndices).sorted()
    }
    
    /// 清除所有选择
    func clearSelection() {
        selectedIndices.removeAll()
        tagButtons.forEach { $0.isSelected = false }
        notifySelectionChanged()
    }
    
    // MARK: - Private Methods
    
    private func createTagButtons() {
        // 清除现有按钮
        tagButtons.forEach { $0.removeFromSuperview() }
        tagButtons.removeAll()
        selectedIndices.removeAll()
        
        // 创建新按钮
        for (index, tag) in tags.enumerated() {
            let button = EPRoleTagsFilterButton()
            button.text = tag
            button.tag = index
            button.addTarget(self, action: #selector(tagButtonTapped(_:)), for: .touchUpInside)
            
            stackView.addArrangedSubview(button)
            tagButtons.append(button)
        }
    }
    
    @objc private func tagButtonTapped(_ sender: EPRoleTagsFilterButton) {
        let index = sender.tag
        
        // 切换选中状态
        if selectedIndices.contains(index) {
            selectedIndices.remove(index)
            sender.isSelected = false
        } else {
            selectedIndices.insert(index)
            sender.isSelected = true
        }
        // 通知选择变更
        notifySelectionChanged()
    }
    
    private func notifySelectionChanged() {
        let selectedTags = getSelectedTags()
        let selectedIndices = getSelectedIndices()
        selectionCallback?(selectedTags, selectedIndices)
    }
}
