//
//  CoinsRechargeGridController.swift

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

import UIKit
import JXPagingView
import Combine
class CoinsRechargeGridController: CLViewController<CoinsRechargeGridView> {
    
    private var cancellables = Set<AnyCancellable>()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDatas()
        setupEvents()
    }
    
    private func setupViews() {
        navigationView.isHidden = true
    }
    
    private func setupDatas(){
        loadBalance()
        loadCoinsTiers()
    }
    
    private func loadBalance(){
        WalletCore.shared.refreshWallet {
            
        }
    }
    
    private func loadCoinsTiers(){
        CLPurchase.shared.loadCoinTiersProducts {[weak self] reponse in
            //self?.container.config(reponse?.productList ?? [])
            self?.handleValidProductsInEpalServer(products: reponse?.productList)
        }
    }
    
    
    
    private func setupEvents(){
        container.header.billListEntryButton.addTarget(self, action: #selector(billListEntryButtonAction), for: .touchUpInside)
        
//        container.$selectIndex.sink { index in
//            
//        }.store(in: &cancellables)
        
    }
    
    // MARK: - helper

    private func handleValidProductsInEpalServer(products: [IAPProducts]?) {
        guard let items = products else {
            return
        }

        container.config(items)

        Hud.showIndicator()
        IAPCore.shared.requestProducts(items) { [weak self] iapIds in
            Hud.hideIndicator()
            var validProducts: [IAPProducts] = []
            for id in iapIds {
                for per in items {
                    if id == per.productId {
                        validProducts.append(per)
                        continue
                    }
                }
            }
            self?.container.config(validProducts)
        }
    }
    
    // MARK: - Action
    @objc func billListEntryButtonAction() {
        let vc = BillDetailListController()
        navigationController?.pushViewController(vc, animated: true)
    }

}

extension CoinsRechargeGridController:JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }

    func listScrollView() -> UIScrollView {
        return container.cv
    }

    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> Void) {
        container.listViewDidScrollCallback = callback
    }
}
