//
//  RoleHomePagerView.swift

//
//  Created by Leon on 2025/7/24.
//

import JXPagingView
import JXSegmentedView
import UIKit

class RoleHomePagerView: CLContainer {
    
    var tapCreateAction: (()-> Void)?
    
    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 headerView: RoleHomePagerHeader!
    private var headerViewHeight: CGFloat = 288
    lazy var aboutVc: RoleHomeAboutController = RoleHomeAboutController()
    lazy var albumVc: RoleHomeAlbumController = RoleHomeAlbumController()

    var createButton: StyleButton!
    
    var roleInfo: AIRoleInfo?

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

        setupViews()
        setupDats()
        setupEvents()
    }

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

    private func setupViews() {
        headerView = {
            let v = RoleHomePagerHeader()
            v.heightChangeBlock = { [weak self] height in
                self?.headerViewHeight = height
                self?.pagingView.resizeTableHeaderViewHeight()
            }
            return v
        }()

        pagingView.mainTableView.backgroundColor = UIColor.clear
        pagingView.pinSectionHeaderVerticalOffset = Int(UIWindow.navBarTotalHeight)
        pagingView.mainTableView.gestureDelegate = self
        addSubview(pagingView)
        pagingView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }

        dataSource.clNormalStyle()
        dataSource.titles = ["About", "Album"]

        segmentedView.listContainer = pagingView.listContainerView
        segmentedView.dataSource = dataSource
        segmentedView.delegate = self
        segmentedView.clNormalStyle()

        controllers.append(aboutVc)
        controllers.append(albumVc)

        createButton = {
            let v = StyleButton()
            v.defaultSecondary(size: .small)
            
            segmentedView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-24)
            }
            v.setTitle("Create", for: .normal)
            v.isHidden = true
            return v
        }()
    }

    private func setupDats() {
    }

    private func setupEvents() {
        headerView.heightChangeBlock = { [weak self] height in
            self?.headerViewHeight = height
            self?.pagingView.resizeTableHeaderViewHeight()
        }
    }
    
    func config(info: AIRoleInfo?) {
        roleInfo = info
        guard let data = info, let userId = data.userId, let aiId = data.aiId else { return }
        
        albumVc.aiId = aiId
        albumVc.userId = userId
        
        refreshCreateButtonHidden()
    }
    
    // MARK: - Action

    
    // MARK: - Helper
    
    private func refreshCreateButtonHidden(){
        guard let info = roleInfo else{return}
        if UserCore.shared.isSelfByUid(uid: info.userId) && segmentedView.selectedIndex == 1{
            createButton.isHidden = false
        }else{
            createButton.isHidden = true
        }
    }
}

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

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

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

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

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

    func pagingView(_: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        let vc = controllers[index]
        return vc
    }

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

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

extension RoleHomePagerView: 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
            }
        }
        // 禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
            && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}
