//
//  WalletMainPagerController.swift

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

import UIKit
import JXPagingView
import JXSegmentedView
import Combine

class WalletMainPagerController: CLBaseViewController {
    var titleView: TitleView!
    
    private let segmentedViewHeight = 40
    private lazy var segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: CGFloat(segmentedViewHeight)))
    private lazy var pagingView = JXPagingListRefreshView(delegate: self)
    private var controllers = [JXPagingViewListViewDelegate]()
    private let dataSource = JXSegmentedTagStyleDataSource()

    var headerViewHeight = 0// 60
    
    lazy var coinsRechargeVc = CoinsRechargeGridController()
    lazy var incomeListVc = CoinsIncomeTableController()
    
    var operateView: CoinsRechargeBottomView!
    
    var viewModel = CoinsRechargeViewModel()
    
    private var cancellables = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupViews()
        setupDatas()
        setupEvents()
        
    }
    
    private func setupViews() {
        let title = "Wallet"
        navigationView.alpha0Title = title
        titleView = {
            let v = TitleView()
            v.title = title
            return v
        }()
        titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: titleView.preCalculateHeight())
        headerViewHeight = Int(titleView.preCalculateHeight())
        
        pagingView.mainTableView.backgroundColor = UIColor.clear
        pagingView.mainTableView.contentInsetAdjustmentBehavior = .never
        pagingView.listContainerView.listCellBackgroundColor = .clear
        if #available(iOS 15.0, *) {
            pagingView.mainTableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        pagingView.mainTableView.gestureDelegate = self
        view.addSubview(pagingView)
        pagingView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
            //make.top.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
        }
        
        //dataSource.clNormalStyle()
        
        let titles = ["Recharge", "Income"]
        dataSource.titles = titles

        segmentedView.listContainer = pagingView.listContainerView
        segmentedView.dataSource = dataSource
        segmentedView.delegate = self
        segmentedView.contentEdgeInsetLeft = 24
        segmentedView.contentEdgeInsetRight = 24
        // segmentedView.clNormalStyle()
        
        operateView = {
            let v = CoinsRechargeBottomView()
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.bottom.equalToSuperview()
            }
            return v
        }()
    }
    
    private func setupDatas(){
        
    }
    
    private func setupEvents(){
        operateView.operateButton.addTarget(self, action: #selector(tapRechargeButton), for: .touchUpInside)
        
//        coinsRechargeVc.container.selectIndex
        coinsRechargeVc.container.$selectProduct.sink {[weak self] product in
            // refresh button title⚠️
        }
    }
    
    // MARK: - Action
    @objc private func tapRechargeButton(){
        
        guard let selectProduct = coinsRechargeVc.container.selectProduct, let productId = selectProduct.productId else{
            return
        }
        
        Hud.showIndicator()
        viewModel.purchase(product: selectProduct) { result, tradeNo in
            Hud.hideIndicator()
            guard let no = tradeNo else{
                return
            }
            
            selectProduct.tradeId = tradeNo
            IAPCore.shared.addPayProductId(productId: productId, tradeId: no)
        }
    }
}

extension WalletMainPagerController: JXSegmentedViewDelegate, JXPagingViewDelegate {
    func tableHeaderViewHeight(in _: JXPagingView) -> Int {
        return Int(headerViewHeight)
    }

    func tableHeaderView(in _: JXPagingView) -> UIView {
        return titleView
    }

    func heightForPinSectionHeader(in _: JXPagingView) -> Int {
        return segmentedViewHeight
    }

    func viewForPinSectionHeader(in _: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in _: JXPagingView) -> Int {
        return dataSource.titles.count
    }

    func pagingView(_: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        if index == 0 {
            return coinsRechargeVc
        } else{
            return incomeListVc
        }
    }

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        operateView.isHidden = index != 0
    }

    func mainTableViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviViewsAlpha(scrollView: scrollView, alphaViews: [navigationView.titleLabel, navigationView.bgView], oppositeViews: [])
    }
}

extension WalletMainPagerController: JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(
        _ gestureRecognizer: UIGestureRecognizer,
        shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 如果是 UICollectionView 的手势，先判断滚动方向
        if let panGesture = otherGestureRecognizer as? UIPanGestureRecognizer,
           let otherView = otherGestureRecognizer.view,
           otherView is UICollectionView {
            let velocity = panGesture.velocity(in: otherView)
            // 横向滚动时禁止
            if abs(velocity.x) > abs(velocity.y) {
                return false
            }
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
            && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}
