//
//  CoinsRechargeGridView.swift

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

import UIKit
import Combine
class CoinsRechargeGridView: UIView{
    var layout = UICollectionViewFlowLayout()
    var cv : UICollectionView!
    var header: CoinsRechargeHeader!

    var headerHeight: CGFloat = 248
    var listViewDidScrollCallback: ((UIScrollView) -> Void)?
    
    var datas = [IAPProducts]()
    
    @Published var selectIndex = 0
    @Published var selectProduct : IAPProducts?
    
    private var cancellables = Set<AnyCancellable>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        let width = floor((UIScreen.width - 24 * 2 - 16) * 0.5)
        let height = 96.0
        
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 0, left: 24, bottom: UIWindow.safeAreaBottom + 136 + 16, right: 24)

        cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.showsHorizontalScrollIndicator = false
        //        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        cv.contentInsetAdjustmentBehavior = .never
        cv.register(CoinsRechargeGridCell.self, forCellWithReuseIdentifier: "CoinsRechargeGridCell")
        cv.register(UICollectionReusableView.self,
                    forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                    withReuseIdentifier: "UICollectionReusableView")
        addSubview(cv)
        cv.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            //make.bottom.equalTo(operateView.snp.top)
            make.bottom.equalToSuperview()
        }

        header = CoinsRechargeHeader()
        
        $selectIndex.sink {[weak self] index in
            guard let self = self else{return}
            if index < self.datas.count{
                self.selectProduct = self.datas[index]
            }
        }.store(in: &cancellables)
    }
    
    func config(_ tiers: [IAPProducts]){
        datas = tiers
        cv.reloadData()
        selectIndex = selectIndex
    }
    
    // MARK: - Helper

}

extension CoinsRechargeGridView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CoinsRechargeGridCell", for: indexPath) as! CoinsRechargeGridCell
        let data = datas[indexPath.item]
        cell.config(data)
        cell.setupSelected(selected: indexPath.item == selectIndex)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectIndex = indexPath.item
        collectionView.reloadData()
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let head = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "UICollectionReusableView",
                for: indexPath
            )
            if header.superview == nil || header.superview != head {
                header.removeFromSuperview()
            }

            head.addSubview(header)
            header.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }

            return head
        }
        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: UIScreen.width, height: headerHeight)
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        listViewDidScrollCallback?(scrollView)
    }
}


