//
//  LeaderboardPagerMainController.swift

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

import JXPagingView
import JXSegmentedView
import UIKit

class LeaderboardPagerMainController: CLBaseViewController {
    var navBgIv: UIImageView!
    var helpGhostButton: EPIconGhostButton!
    
    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 = JXSegmentedTitleDataSource()

    var headerViewHeight = 0// 60

    private lazy var chatLeaderboardVc = LeaderboardListController()
    private lazy var hearbeatLeaderboardVc = LeaderboardListController()
    private lazy var giftLeaderboardVc = LeaderboardListController()

    var types = [DiscoverRankType.chat, DiscoverRankType.heartbeat,  DiscoverRankType.gift]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
        let title = "Leaderboard"
        navigationView.alpha0Title = title
        navigationView.bgView.alpha = 0
        
        navBgIv = {
            let v = UIImageView()
            v.image = UIImage(named: "discover_home_bg_rank")
            navigationView.insertSubview(v, aboveSubview: navigationView.bgView)
            v.snp.makeConstraints { make in
                make.leading.top.trailing.equalToSuperview()
                make.height.equalTo(v.snp.width).multipliedBy(v.image!.size.height/v.image!.size.width)
            }
            return v
        }()
        
        helpGhostButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .faq)
            v.addTarget(self, action: #selector(tapHelpButton), for: .touchUpInside)
            navigationView.rightStackH.addArrangedSubview(v)
            navigationView.paddingRightForRightStack = 16
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            return v
        }()

        titleView = {
            let v = TitleView()
            v.optionInnerTopPadding = 16
            v.title = title
            return v
        }()
        titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: titleView.preCalculateHeight())
        headerViewHeight = Int(titleView.preCalculateHeight())
//        dlog("calclulate: \(headerViewHeight)")

        pagingView.mainTableView.backgroundColor = UIColor.clear
        pagingView.mainTableView.contentInsetAdjustmentBehavior = .never
        pagingView.mainTableView.sectionHeaderHeight = 0
        pagingView.mainTableView.sectionFooterHeight = 0
        pagingView.mainTableView.estimatedSectionHeaderHeight = 0
        pagingView.mainTableView.estimatedSectionFooterHeight = 0
        pagingView.mainTableView.estimatedRowHeight = 0
        
        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()
        var titles = [String]()
        for per in types {
            titles.append(per.localizedText)
        }
        dataSource.titles = titles

        segmentedView.listContainer = pagingView.listContainerView
        segmentedView.dataSource = dataSource
        segmentedView.delegate = self
        segmentedView.clNormalStyle()
        
        chatLeaderboardVc.type = .chat
        hearbeatLeaderboardVc.type = .heartbeat
        giftLeaderboardVc.type = .gift
    }

    private func setupDatas() {
    }

    private func setupEvents() {
    }
    
    // MARK: Action
    @objc private func tapHelpButton(){
        let content = "热聊榜以AI聊天会话数高低排名\n心动榜以AI角色所有对话者产生的心动值之和的高低排名\n礼物榜以AI角色所收到礼物打赏价值之和排名"
        let alert = Alert(title: "Tips", text: content)
        let action1 = AlertAction(title: "Got it", actionStyle: .confirm) {
        }
        alert.addAction(action1)
        alert.show()
    }
}

extension LeaderboardPagerMainController: 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 chatLeaderboardVc
        } else if index == 1 {
            return hearbeatLeaderboardVc
        } else {
            return giftLeaderboardVc
        }
    }

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
    }

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

extension LeaderboardPagerMainController: 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)
    }
}
