//
//  YHResourceCategoryView.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/24.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

protocol YHResourceCategoryViewDelegate: AnyObject {
    func categoryView(_ view: YHResourceCategoryView, didSelectCategories categories: [YHResourceCategory], isSet: Bool)
}

class YHResourceCategoryView: UIView {
    
    weak var delegate: YHResourceCategoryViewDelegate?
    
    private var categories: [YHResourceCategory] = []
    private var selectedCategories: [YHResourceCategory] = []
    
    // MARK: - UI Components
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 8
        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 100, right: 16) // 增加底部间距，为按钮留出空间
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(YHResourceCategoryCell.self, forCellWithReuseIdentifier: "YHResourceCategoryCell")
        collectionView.showsVerticalScrollIndicator = false
        return collectionView
    }()
    
    // 底部按钮容器视图
    private lazy var bottomButtonContainer: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        // 添加顶部阴影
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: -2)
        view.layer.shadowOpacity = 0.05
        view.layer.shadowRadius = 4
        return view
    }()
    
    private lazy var resetButton: UIControl = {
        let btn = UIControl()
        let label = UILabel()
        label.text = "重置"
        label.textColor = .brandGrayColor8
        label.font = UIFont.PFSC_M(ofSize: 12)
        let imageView = UIImageView(image: UIImage(named: "resource_filter_reset"))
        btn.addSubview(label)
        btn.addSubview(imageView)
        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.bottom.equalToSuperview()
        }
        imageView.snp.makeConstraints { make in
            make.bottom.equalTo(label.snp.top)
            make.centerX.equalTo(label)
            make.width.height.equalTo(24)
        }
        btn.addTarget(self, action: #selector(resetButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    private lazy var confirmButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("筛选", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 15)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.layer.cornerRadius = 3
        btn.addTarget(self, action: #selector(confirmButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - Setup
    
    private func setupUI() {
        clipsToBounds = true
        backgroundColor = .white
        
        addSubview(collectionView)
        addSubview(bottomButtonContainer)
        bottomButtonContainer.addSubview(resetButton)
        bottomButtonContainer.addSubview(confirmButton)
        
        setupConstraints()
    }
    
    private func setupConstraints() {
        collectionView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview() // collection view占满整个视图
        }
        
        bottomButtonContainer.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(74) // 按钮容器高度
        }
        
        resetButton.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(12)
            make.width.equalTo(60)
            make.height.equalTo(46)
        }
        
        confirmButton.snp.makeConstraints { make in
            make.left.equalTo(resetButton.snp.right)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(12)
            make.height.equalTo(46)
        }
    }
    
    // MARK: - Public Methods
    
    /// 设置分类数据（从外部传入，通常来自API）
    /// - Parameter categories: 分类数组
    func setCategories(_ categories: [YHResourceCategory]) {
        self.categories = categories
        collectionView.reloadData()
    }
    
    /// 设置已选中的分类
    /// - Parameter categories: 已选中的分类数组
    func setSelectedCategories(_ categories: [YHResourceCategory]) {
        selectedCategories = categories
        collectionView.reloadData()
    }
    
    // MARK: - Actions
    
    @objc private func resetButtonClicked() {
        // 重置：清空所有选择
        selectedCategories.removeAll()
        collectionView.reloadData()
        delegate?.categoryView(self, didSelectCategories: selectedCategories, isSet: false)
    }
    
    @objc private func confirmButtonClicked() {
        delegate?.categoryView(self, didSelectCategories: selectedCategories, isSet: true)
    }
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension YHResourceCategoryView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard categories.count > indexPath.item,
              let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YHResourceCategoryCell", for: indexPath) as? YHResourceCategoryCell else {
            return UICollectionViewCell()
        }
        
        let category = categories[indexPath.item]
        let isSelected = selectedCategories.contains { $0.id == category.id }
        cell.configure(with: category, isSelected: isSelected)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let category = categories[indexPath.item]
        
        if category.id == YHResourceCategory.allCategory.id {
            // 全部行业的处理逻辑
            if selectedCategories.contains(where: { $0.id == YHResourceCategory.allCategory.id }) {
                selectedCategories.removeAll()
            } else {
                selectedCategories = [category]
            }
        } else {
            // 其他行业的处理逻辑
            selectedCategories.removeAll(where: { $0.id == YHResourceCategory.allCategory.id })
            // 原有的切换逻辑
            // 切换选中状态（支持多选）
            if let index = selectedCategories.firstIndex(where: { $0.id == category.id }) {
                // 如果已选中，则取消选中
                selectedCategories.remove(at: index)
            } else {
                // 如果未选中，则添加到选中列表
                selectedCategories.append(category)
            }
        }
                
        // 刷新UI
        collectionView.reloadData()
        
        // 通知代理（不自动关闭，用户需要点击"筛选"按钮）
        delegate?.categoryView(self, didSelectCategories: selectedCategories, isSet: false)
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
extension YHResourceCategoryView: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 计算每行三个cell的宽度
        let sectionInset = 16.0 // 左右边距
        let minimumInteritemSpacing = 8.0 // cell间距
        let totalInset = sectionInset * 2 + minimumInteritemSpacing * 2 // 总的边距和间距
        let availableWidth = collectionView.frame.width - totalInset
        let cellWidth = availableWidth / 3.0 // 每行三个
        
        return CGSize(width: cellWidth, height: 44) // 固定高度
    }
}

// MARK: - YHResourceCategoryCell
class YHResourceCategoryCell: UICollectionViewCell {
    
    private lazy var iconLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 18)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textAlignment = .center
        label.textColor = .brandGrayColor8
        label.numberOfLines = 1
        label.adjustsFontSizeToFitWidth = true // 自动调整字体大小以适应宽度
        label.minimumScaleFactor = 0.8
        return label
    }()
    
    private lazy var containerStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.spacing = 4
        stack.alignment = .center
        stack.distribution = .fill
        return stack
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = UIColor.brandGrayColor2
        layer.cornerRadius = 2
        layer.borderWidth = 1
        layer.borderColor = UIColor.clear.cgColor
        
        contentView.addSubview(containerStackView)
        containerStackView.addArrangedSubview(iconLabel)
        containerStackView.addArrangedSubview(titleLabel)
        
        containerStackView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.left.greaterThanOrEqualToSuperview().offset(8)
            make.right.lessThanOrEqualToSuperview().offset(-8)
        }
        
        iconLabel.setContentHuggingPriority(.required, for: .horizontal)
        titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    }
    
    func configure(with category: YHResourceCategory, isSelected: Bool) {
//        // 设置图标（如果有）
//        if !category.icon.isEmpty {
//            iconLabel.text = category.icon
//            iconLabel.isHidden = false
//        } else {
//            iconLabel.isHidden = true
//        }
        iconLabel.isHidden = true
        titleLabel.text = category.name
        
        if isSelected {
            layer.borderColor = UIColor.brandGrayColor8.cgColor
            titleLabel.font = UIFont.PFSC_B(ofSize: 13)
            titleLabel.textColor = UIColor.brandGrayColor8
        } else {
            layer.borderColor = UIColor.clear.cgColor
            titleLabel.font = UIFont.PFSC_R(ofSize: 13)
            titleLabel.textColor = UIColor.brandGrayColor7
        }
    }
}
