//
//  CLRoleTagsView.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/16.
//

import UIKit

class CLRoleTagsView: UIView {
    
//    let tags = ["#浪漫", "#温柔", "#多愁善感", "#深情", "#this is good", "#沙瓦迪", "#科技哈", "#等好a", "#a"]
    // 防止死循环的标志位
    private var isUpdatingTagModels = false
    
    var tagModels: [CLRoleTagsModel] = [
//        CLRoleTagsModel(name: "#浪漫浪漫浪漫浪漫浪漫浪漫浪漫浪漫浪漫漫浪漫浪漫浪漫漫浪漫浪漫浪漫漫浪漫浪漫浪漫", isSelected: false),
//        CLRoleTagsModel(name: "#温柔", isSelected: false),
//        CLRoleTagsModel(name: "#多愁善感", isSelected: false),
//        CLRoleTagsModel(name: "#this is good", isSelected: false),
//        CLRoleTagsModel(name: "#沙瓦迪", isSelected: false),
//        CLRoleTagsModel(name: "#科技哈", isSelected: false),
//        CLRoleTagsModel(name: "#等好a", isSelected: false),
//        CLRoleTagsModel(name: "#a", isSelected: false),
//        CLRoleTagsModel(name: "#浪漫", isSelected: false),
    ] {
        didSet {
            // 防止死循环：如果正在更新，不执行
            guard !isUpdatingTagModels else { return }
            
            // 确保第0个位置是"全部"标签
            ensureAllTagAtFirst()
            self.collectionView.reloadData()
        }
    }
    
    // 标签选择回调：返回选中的标签ID数组，nil表示全部标签
    var onTagSelected: (([String]?) -> Void)?
    
    // 确保第0个位置是"全部"标签
    private func ensureAllTagAtFirst() {
        // 如果 tagModels 为空，添加"全部"标签
        if tagModels.isEmpty {
            isUpdatingTagModels = true
            tagModels = [CLRoleTagsModel(name: "All", id: "0", isSelected: true)]
            isUpdatingTagModels = false
            return
        }
        
        // 检查第0个位置是否是"全部"标签
        let allTagName = "All"
        if tagModels.first?.name != allTagName {
            // 如果第0个位置不是"全部"标签，插入到第0个位置
            let allTag = CLRoleTagsModel(name: allTagName, id: "0", isSelected: true)
            isUpdatingTagModels = true
            tagModels.insert(allTag, at: 0)
            isUpdatingTagModels = false
        } else {
            // 如果第0个位置是"全部"标签，确保它是选中状态（如果没有其他标签选中）
            let hasOtherSelected = tagModels.dropFirst().contains { $0.isSelected }
            if !hasOtherSelected && !tagModels[0].isSelected {
                isUpdatingTagModels = true
                tagModels[0].isSelected = true
                isUpdatingTagModels = false
            }
        }
    }
    
    lazy var collectionView: AutoHeightCollectionView = {
        let layout = TagFlowLayout()
        layout.interItemSpacing = 10       // 横向间距
        layout.lineSpacing = 8
        layout.maxLineWidth = UIScreen.width - 20.0
        layout.delegate = self

        let collectionView = AutoHeightCollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.setContentHuggingPriority(.required, for: .vertical)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(RoleTagCollectionCell.self, forCellWithReuseIdentifier: "RoleTagCollectionCell")
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupSubviews()
//        setupDatas()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: Subviews
    func setupSubviews() {
        
        addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
        
    // MARK: data
    private func setupDatas() {
        
    }
}

extension CLRoleTagsView: UICollectionViewDataSource, UICollectionViewDelegate, TagFlowLayoutDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        tagModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: RoleTagCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "RoleTagCollectionCell", for: indexPath) as! RoleTagCollectionCell
        
        cell.setupData(model: tagModels[indexPath.item])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedModel = tagModels[indexPath.item]
        print("点击了标签：\(selectedModel.name)")
        
        // 如果点击的是"全部"标签（第0个位置）
        if indexPath.item == 0 {
            // 如果"全部"标签已选中，不做任何操作
            if selectedModel.isSelected {
                return
            }
            // 取消所有其他标签的选中状态
            for i in 1..<tagModels.count {
                tagModels[i].isSelected = false
            }
            // 选中"全部"标签
            tagModels[0].isSelected = true
            collectionView.reloadData()
            // 通知外部，选中全部标签（tagId 为 nil）
            onTagSelected?(nil)
        } else {
            // 点击的是其他标签，支持多选
            tagModels[indexPath.item].isSelected.toggle()
            
            if tagModels[indexPath.item].isSelected {
                // 选中了其他标签，取消"全部"标签的选中状态
                tagModels[0].isSelected = false
                
                // 获取所有选中的非 All 标签的 ID
                let selectedIds = tagModels.dropFirst().filter { $0.isSelected }.map { $0.id }
                collectionView.reloadData()
                // 通知外部，传递选中的标签ID数组
                onTagSelected?(selectedIds.isEmpty ? nil : selectedIds)
            } else {
                // 取消选中其他标签
                // 获取所有选中的非 All 标签的 ID
                let selectedIds = tagModels.dropFirst().filter { $0.isSelected }.map { $0.id }
                
                if selectedIds.isEmpty {
                    // 如果没有其他标签选中，默认选中"全部"标签
                    tagModels[0].isSelected = true
                    collectionView.reloadData()
                    // 通知外部，选中全部标签（tagId 为 nil）
                    onTagSelected?(nil)
                } else {
                    collectionView.reloadData()
                    // 通知外部，传递剩余的选中标签ID数组
                    onTagSelected?(selectedIds)
                }
            }
        }
    }
    
    // 根据文字计算 size
    func collectionView(_ collectionView: UICollectionView,
                        layout: TagFlowLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = tagModels[indexPath.item].name
        let font = UIFont.boldSystemFont(ofSize: 12)
        let w = text.size(withAttributes: [.font: font]).width + 20   // 左右 10 pt padding
        return CGSize(width: min(w, layout.maxItemWidth), height: 23)
    }
    
}


final class AutoHeightCollectionView: UICollectionView {
    override var contentSize: CGSize {
        didSet { invalidateIntrinsicContentSize() }
    }
    override var intrinsicContentSize: CGSize {
        CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}
