//
//  ChatBackgroundCell.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/27.
//

import UIKit
import SnapKit

struct BackgroundRow: RowModel {
    let count: Int
    var cellReuseID: String { "ChatBackgroundCell" }
    func cellHeight(tableWidth: CGFloat) -> CGFloat { 
        // 使用 UITableView.automaticDimension 让 cell 自动计算高度
        return UITableView.automaticDimension
    }
}

class ChatBackgroundCell: UITableViewCell, CellConfigurable {
    
    private var collectionHeight: Constraint!
    private var itemCount: Int = 6 // 默认6个item
    private var layout: UICollectionViewFlowLayout!

    lazy var collectionView: UICollectionView = {
        layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10.0
        layout.minimumInteritemSpacing = 10.0
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isScrollEnabled = false
        collectionView.backgroundColor = .clear
        collectionView.register(ChatBgCollectionCell.self, forCellWithReuseIdentifier: "ChatBgCollectionCell")
        return collectionView
    }()
    
    func configure(with row: RowModel) {
        guard let row = row as? BackgroundRow else { return }
        
        // 更新数据源
        self.itemCount = row.count
        
        // 延迟更新，确保 collectionView 的 frame 已经确定
        DispatchQueue.main.async { [weak self] in
            self?.updateCollectionViewLayout()
        }
    }
    
    private var lastCalculatedWidth: CGFloat = 0
    
    private func updateCollectionViewLayout() {
        guard collectionView.frame.width > 0 else { return }
        
        // 避免重复计算
        if abs(lastCalculatedWidth - collectionView.frame.width) < 1.0 {
            return
        }
        lastCalculatedWidth = collectionView.frame.width
        
        // 重新加载数据，触发 sizeForItemAt 计算
        collectionView.reloadData()
        
        // 强制布局更新
        collectionView.layoutIfNeeded()
        
        // 获取准确的内容高度并更新约束
        let contentHeight = collectionView.collectionViewLayout.collectionViewContentSize.height
        if contentHeight > 0 {
            collectionHeight.update(offset: contentHeight)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        configureViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configureViews() {
        contentView.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.width.equalToSuperview()
            make.bottom.equalToSuperview().priority(999) // 让底部约束优先级稍低
            collectionHeight = make.height.equalTo(100).priority(1000).constraint // 初始占位高度
        }
    }
    
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        // 如果 collectionView 还没有正确的 frame，先设置一个临时的
        if collectionView.frame.width == 0 {
            collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: 100)
            updateCollectionViewLayout()
        }
        
        // 返回计算后的尺寸
        return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
    }

}

extension ChatBackgroundCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChatBgCollectionCell", for: indexPath) as! ChatBgCollectionCell
        
        // 这里可以根据 indexPath 配置不同的 cell 内容
        // 例如：cell.configure(with: data[indexPath.item])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let availableWidth = collectionView.frame.width - layout.sectionInset.left - layout.sectionInset.right
        let itemWidth = (availableWidth - 2 * layout.minimumInteritemSpacing) / 3.0
        let itemHeight = itemWidth * (116.0 / 87)
        return CGSize(width: itemWidth, height: itemHeight)
    }
}
