//
//  EncounterAICardAlbumView.swift

//
//  Created by Leon on 2025/9/11.
//
import UIKit

class EncounterAICardAlbumView: UIView {
    var cv: UICollectionView!
    var layout: UICollectionViewFlowLayout!
    
    // 数据源
    var card:  MeetCard?
    private var albumItems: [AlbumPhotoItem] = []

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        //backgroundColor = .random

        let cardWidth = UIScreen.width - 12 * 2
        let itemW = floor((cardWidth - 24 * 2 - 16) * 0.5) as CGFloat
        let itemH = itemW

        layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 12, left: 24, bottom: 12 + UIWindow.safeAreaBottom, right: 24)

        cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.register(RoleHomeAlbumGridCell.self, forCellWithReuseIdentifier: "RoleHomeAlbumGridCell")
        cv.delegate = self
        cv.dataSource = self
        cv.isScrollEnabled = false
        addSubview(cv)

        cv.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo(764) // Temp height!
        }
    }
    
    // MARK: - Public Methods
    func configCard(card: MeetCard?){
        self.card = card
    }
    
    func config(_ albumItems: [AlbumPhotoItem]) {
        
        self.albumItems = albumItems
        cv.reloadData()
        
        // 计算动态高度
        let cardWidth = UIScreen.width - 12 * 2
        let itemW = floor((cardWidth - 24 * 2 - 16) * 0.5) as CGFloat
        let itemH = itemW
        
        let itemsPerRow = 2 // 每行2个item
        let lineSpacing: CGFloat = 16
        let topInset: CGFloat = 12
        let bottomInset: CGFloat = 12 + UIWindow.safeAreaBottom
        
        var calculatedHeight: CGFloat
        
        if albumItems.count > 0 {
            // 有图片时，根据实际数量计算行数
            let rowCount = ceil(CGFloat(albumItems.count) / CGFloat(itemsPerRow))
            calculatedHeight = topInset + (rowCount * itemH) + ((rowCount - 1) * lineSpacing) + bottomInset
        } else {
            // 无图片时，留足两行cell高度给占位图
            let emptyRowCount: CGFloat = 2
            calculatedHeight = topInset + (emptyRowCount * itemH) + ((emptyRowCount - 1) * lineSpacing) + bottomInset
        }
        
        // 更新collectionView的高度约束
        cv.snp.updateConstraints { make in
            make.height.equalTo(calculatedHeight)
        }
        
        if albumItems.count > 0{
            hideEmpty()
        }else{
            showEmpty(text: "No photos")
        }
    }
}

extension EncounterAICardAlbumView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return albumItems.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RoleHomeAlbumGridCell", for: indexPath) as! RoleHomeAlbumGridCell
        cell.usedInMeetCard = true
        let albumItem = albumItems[indexPath.item]
        cell.config(data: albumItem)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("did Select Meet album ItemAt \(indexPath)")
        guard let aiId = card?.aiId else {return}
        
        var photoModels = [PhotoBrowserModel]()
        
        for (index, per) in albumItems.enumerated() {
            let perAlbum = per

            let model = PhotoBrowserModel()
            model.aiAlbum = perAlbum
            model.aiId = aiId
            model.imageUrl = perAlbum.getImgUrl()
            if index == indexPath.item{
                if let cell = collectionView.cellForItem(at: indexPath) as? RoleHomeAlbumGridCell{
                    model.image = cell.imageView.image
                    model.sourceRect = cell.screenRect ?? .zero
                }
            }
            photoModels.append(model)
        }
        
        ImageBrowser.show(models: photoModels, index: indexPath.item, type: .roleOthersInAlbum)
    }
}
