//
//  RolesRootPageView.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/14.
//

import JXPagingView
import JXSegmentedView
import UIKit
import Combine

class RolesRootPageView: CLContainer {
    
    let itemWidth: CGFloat = (UIScreen.width - 30.0) / 2.0
    var jumpPublisher: AnyPublisher<JumpTarget, Never> { topView.jumpPublisher }
    
    //    private lazy var pagingView = JXPagingListRefreshView(delegate: self)
    //    lazy var headerView:
    
    // 刷新和加载回调
    var onRefresh: (() -> Void)?
    var onLoadMore: (() -> Void)?
    
    var data: [RoleItem] = []
    var hasMoreData: Bool = true  // 是否还有更多数据
    
    let remind: [String] = [
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]"
    ]
    
    lazy var topView: CLTopHeaderView = {
        let view = CLTopHeaderView()
        return view
    }()
    
    lazy var tagsView: CLRoleTagsView = {
        let tagsView = CLRoleTagsView()
        return tagsView
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = CLWaterfallLayout()
        layout.columnCount = 2
        layout.delegate = self
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(CLRoleCollectionCell.self, forCellWithReuseIdentifier: "CLRoleCollectionCell")
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
        setupRefresh()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        addSubview(self.topView)
        //        addSubview(tagsChooseView)
        addSubview(tagsView)
        addSubview(collectionView)
        
        topView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(UIDevice().navHeight)
        }
        
        tagsView.snp.makeConstraints { make in
            make.right.left.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(0)
        }
        
        collectionView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(tagsView.snp.bottom).offset(0)
        }
    }
    
    // 设置下拉刷新和上拉加载
    private func setupRefresh() {
        // 下拉刷新
        let header = RefreshHeaderAnimator(refreshingBlock: { [weak self] in
            self?.onRefresh?()
        })
        // 设置忽略的 contentInset，确保下拉刷新动画正常显示
//        header.ignoredScrollViewContentInsetTop = collectionView.contentInset.top
        collectionView.mj_header = header
        
        // 上拉加载
        let footer = RefreshFooterAnimator(refreshingBlock: { [weak self] in
            self?.onLoadMore?()
        })
        collectionView.mj_footer = footer
    }
    
    func config(_ data: [RoleItem]?, isFirstPage: Bool){
        let rows = data ?? []
        
        if isFirstPage {
            // 下拉刷新或首次加载：重置数据
            self.data = rows
            // 重置上拉加载状态
            collectionView.mj_footer?.resetNoMoreData()
        } else {
            // 上拉加载：追加数据
            if !rows.isEmpty {
                self.data.append(contentsOf: rows)
            }
        }
        
        // 判断是否还有更多数据
        // 如果返回的数据为空，或者数据量小于每页数量（10），说明没有更多数据了
        if rows.isEmpty || rows.count < 10 {
            hasMoreData = false
        } else {
            hasMoreData = true
        }
        self.collectionView.reloadData()
    }
    
    // 结束刷新动画
    func endRefreshing() {
        collectionView.mj_header?.endRefreshing()
        collectionView.mj_footer?.endRefreshing()
    }
    
    func configureTags(_ data: [RoleTagItem]?) {
        guard let tags = data else {
            self.tagsView.tagModels = []
            return
        }
        self.tagsView.tagModels = tags.map(CLRoleTagsModel.init)
    }
}

extension RolesRootPageView: UICollectionViewDelegate, UICollectionViewDataSource, WaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CLRoleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CLRoleCollectionCell", for: indexPath) as! CLRoleCollectionCell
        
        // 使用 indexPath.item 而不是 indexPath.row（UICollectionView 应该使用 item）
        guard indexPath.item < data.count else {
            return cell
        }
        cell.setupData(item: data[indexPath.item])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if data.count > indexPath.item {
            let item = data[indexPath.item]
            let sessionId = "439217670979585@r@t"
            AppRouter.goChatVC(conversationId: sessionId, title: item.name, complete: nil)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView,
                            layout: CLWaterfallLayout,
                            heightForItemAt indexPath: IndexPath) -> CGFloat {
        // 防止数组越界
        guard indexPath.item < data.count else {
            return 0
        }
        
        let model = data[indexPath.item]

        let coverH = itemWidth * (4.0 / 3.0)
        // 文字高度
        let maxLines = 3
        let font = UIFont.systemFont(ofSize: 12)
        let lineHeight = font.lineHeight        // 15 pt 字体 ≈ 17.4 pt
        let maxHeight = lineHeight * CGFloat(maxLines)

        // 真实文本高度（不会超过 maxHeight）
        let textSize = model.name.boundingRect(
            with: CGSize(width: itemWidth - 20, height: maxHeight), // 高度封顶
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: [.font: font],
            context: nil).size

        // 取最小值，保证不足 3 行时按实际算，超过 3 行时截断在 3 行高
        let textH = min(textSize.height, maxHeight)
        
        // 防止 remind 数组越界，使用模运算或默认值
        let remindIndex = indexPath.item % remind.count
        let remindText = remind[remindIndex]
        let remindH = remindText.boundingRect(
            with: CGSize(width: itemWidth - 20.0, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: UIFont.boldSystemFont(ofSize: 10)],
            context: nil).height
        
        return coverH + 10.0 + textH + 5.0 + remindH
    }
}

//extension RolesRootPageView: JXPagingViewDelegate {
//    func tableHeaderViewHeight(in _: JXPagingView) -> Int {
//        return 100
//    }
//
//    func tableHeaderView(in _: JXPagingView) -> UIView {
//        return headerView
//    }
//
//    func heightForPinSectionHeader(in _: JXPagingView) -> Int {
//        return headerPinHeadHeight
//    }
//
//    func viewForPinSectionHeader(in _: JXPagingView) -> UIView {
//        return pinHeaderView
//    }
//
//    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) {
//        if segmentedView == pinHeaderView.segmentedView {
//            refreshSubTagsSegmentView()
//        }
////        else if segmentedView == pinHeaderView.subSegementedView {
////            let selectTag = tagsNodes[index]
////            if let currentVc = controllers[pinHeaderView.segmentedView.selectedIndex] as? DiscoverRolesGridController {
////                currentVc.tryLoad(code: selectTag.code!)
////            }
////        }
//    }
//
//    func mainTableViewDidScroll(_ scrollView: UIScrollView) {
//        NaviAlphaHandle.changeNaviViewsAlpha(scrollView: scrollView, alphaViews: [bgBdView, navigationView?.bgView], oppositeViews: [])
//    }
//}

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