//
//  RoleHomeAboutView.swift

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

import UIKit

let giftCountOnePage = 12
let giftItemWidth = floor((UIScreen.width - 40 * 2 - 12 * 3) / 4.0) as CGFloat
let giftItemHeight: CGFloat = giftItemWidth + 24

class RoleHomeAboutView: CLContainer {
    var container: LTScrollContainer!

    // Data panel
    var likePanelItem: HomeAboutDataPanelItem!
    var chatPanelItem: HomeAboutDataPanelItem!
    var peoplePanelItem: HomeAboutDataPanelItem!
    var giftContainer: UIView!
    var giftPanelItem: HomeAboutDataPanelItem!

    // Introduction
    var introductionLabel: LineSpaceLabel!
    var expendButton: EPIconGhostButton!

    // Gifts - 修改为外层横向滚动
    var outerCollectionView: UICollectionView!
    var pageControl: CLPageControl!
    
    // 礼物数据
    var giftsData: [AIRoleGiftReceivedList] = []
    var currentPage: Int = 0

    var info: AIRoleInfo?

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

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

    private func setupViews() {
        container = {
            let v = LTScrollContainer()
            v.stack.spacing = 16
            v.stackEdge = UIEdgeInsets(top: 12, left: 0, bottom: 16, right: 0)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        backgroundColor = .random

        setupCommonDataPanel()
        setupIntroduction()
        setupGiftsView()
    }

    private func setupCommonDataPanel() {
        let block = UIView()
        block.backgroundColor = .c.csbn
        block.layer.cornerRadius = 16
        block.layer.masksToBounds = true
        container.stack.addArrangedSubview(block)
        block.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            make.height.equalTo(80)
        }

        let stackH = {
            let v = UIStackView()
            v.spacing = 0
            v.distribution = .fillEqually
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalToSuperview().offset(-16)
                make.centerY.equalToSuperview()
            }
            return v
        }()

        likePanelItem = {
            let v = HomeAboutDataPanelItem()
            v.countLabel.text = "0"
            v.tipLabel.text = "Liked"
            stackH.addArrangedSubview(v)
            return v
        }()

        chatPanelItem = {
            let v = HomeAboutDataPanelItem()
            v.countLabel.text = "0"
            v.tipLabel.text = "Chats"
            stackH.addArrangedSubview(v)
            return v
        }()

        peoplePanelItem = {
            let v = HomeAboutDataPanelItem()
            v.countLabel.text = "0"
            v.tipLabel.text = "People"
            stackH.addArrangedSubview(v)
            return v
        }()

        giftPanelItem = {
            let v = HomeAboutDataPanelItem()
            v.countLabel.text = "0"
            #warning("translate")
            v.tipLabel.text = "CrushCoin"
            stackH.addArrangedSubview(v)
            return v
        }()
    }

    private func setupIntroduction() {
        let block = UIView()
        block.backgroundColor = .c.csbn
        block.layer.cornerRadius = 16
        block.layer.masksToBounds = true
        container.stack.addArrangedSubview(block)
        block.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            // make.height.equalTo(80)
        }

        let titleLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tts
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.top.equalToSuperview().offset(16)
            }
            return v
        }()

        let stackH = {
            let v = UIStackView()
            v.spacing = 0
            v.alignment = .bottom
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalToSuperview().offset(-16)
                make.top.equalTo(titleLabel.snp.bottom).offset(8)
                make.bottom.equalToSuperview().offset(-16)
            }
            return v
        }()

        introductionLabel = {
            let v = LineSpaceLabel()
            let typography = CLSystemToken.typography(token: .tbm)
            v.textColor = .text
            v.config(typography)
            v.numberOfLines = 3
            stackH.addArrangedSubview(v)
            return v
        }()

        expendButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .xs, iconCode: .iconFullimage)
            v.addTarget(self, action: #selector(tapExpandButton), for: .touchUpInside)
            stackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            return v
        }()

        titleLabel.text = "Introduction"
//        #warning("test")
//        introductionLabel.text = "She is a new and beautiful teacher and has just graduated. You are the most rebellious student of the whole school with some sth.She is a new and beautiful teacher and has just graduated. You are the most rebellious student of the whole school with some."
    }

    private func setupGiftsView() {
        let block = UIView()
        block.backgroundColor = .c.csbn
        block.layer.cornerRadius = 16
        block.layer.masksToBounds = true
        container.stack.addArrangedSubview(block)
        block.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
        }
        self.giftContainer = block

        let titleLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tts
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.top.equalToSuperview().offset(16)
            }
            return v
        }()
        titleLabel.text = "Gifts"

        // 外层横向滚动的CollectionView
        let outerLayout = UICollectionViewFlowLayout()
        let widthOfOut = UIScreen.width - 24*2
        outerLayout.itemSize = CGSize(width: widthOfOut, height: 200) // 初始高度，后续会动态调整
        outerLayout.scrollDirection = .horizontal
        outerLayout.minimumLineSpacing = 0
        outerLayout.minimumInteritemSpacing = 0
        
        outerCollectionView = {
            let v = UICollectionView(frame: .zero, collectionViewLayout: outerLayout)
            v.backgroundColor = .c.csbn
            v.showsHorizontalScrollIndicator = false
            v.isPagingEnabled = true
            v.register(GiftPageCell.self, forCellWithReuseIdentifier: "GiftPageCell")
            v.dataSource = self
            v.delegate = self
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.height.equalTo(160) // 初始高度，后续会动态调整
            }
            return v
        }()

        // PageControl
        pageControl = {
            let v = CLPageControl()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(outerCollectionView.snp.bottom).offset(8)
                make.bottom.equalToSuperview().offset(-16)
            }
            return v
        }()
    }

    // MARK: - Public

    func config(info: AIRoleInfo?) {
        self.info = info
        guard let data = info else { return }

        introductionLabel.text = data.introduction
        
        if UserCore.shared.isSelf(id: info?.userId){
            giftPanelItem.isHidden = false
        }else{
            giftPanelItem.isHidden = true
        }
    }

    func configStat(data: AIRoleStatisticsResponse?) {
        guard let stat = data else { return }
//        likePanelItem.countLabel.text = String.thousandString(stat.likedNum ?? 0)
//        chatPanelItem.countLabel.text = String.thousandString(stat.chatNum ?? 0)
//        peoplePanelItem.countLabel.text = String.thousandString(stat.conversationNum ?? 0)
//        giftPanelItem.countLabel.text = String.thousandString(float: (Double(stat.coinNum ?? 0)*0.01))
        
        likePanelItem.countLabel.text = String.displayNumber(NSNumber(value: stat.likedNum ?? 0), scale: 1)
        chatPanelItem.countLabel.text = String.displayNumber(NSNumber(value: stat.chatNum ?? 0), scale: 1) //String.thousandString(stat.chatNum ?? 0)
        peoplePanelItem.countLabel.text = String.displayNumber(NSNumber(value: stat.conversationNum ?? 0), scale: 1)//String.thousandString(stat.conversationNum ?? 0)
        giftPanelItem.countLabel.text = String.displayNumber(NSNumber(value: (Double(stat.coinNum ?? 0)*0.01)), scale: 1)//String.thousandString(float: (Double(stat.coinNum ?? 0)*0.01))
    }

    func configGifts(data: [AIRoleGiftReceivedList]?) {
        //guard let gifts = data else { return }
        
        giftsData = data ?? []
        
//        #warning("test")
//        giftsData = []//Array(gifts.prefix(3))

        if giftsData.count > 0{
            outerCollectionView.isHidden = false
            pageControl.isHidden = false
            giftContainer.hideEmpty()
        }else{
            giftContainer.showStartYEmpty(text: "No gift yet", startY: 52)
            outerCollectionView.isHidden = true
            pageControl.isHidden = true
            return
        }
        
        // 计算总页数（每页最多12个礼物）
        let totalPages = max(1, (giftsData.count) / giftCountOnePage)
        
        // 动态计算高度
        let giftHeight: CGFloat = giftItemHeight
        let rowSpacing: CGFloat = 12.0
        var rows = 1.0
        if giftsData.count > 8{
            rows = 3.0
        }else if giftsData.count > 4{
            rows = 2.0
        }
        let calculatedHeight = giftHeight * rows + rowSpacing*(rows-1)
        
        // 更新outerCollectionView的高度约束
        outerCollectionView.snp.updateConstraints { make in
            make.height.equalTo(calculatedHeight)
        }
        
        // 更新layout的itemSize
        if let layout = outerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            let widthOfOut = UIScreen.width - 24*2
            layout.itemSize = CGSize(width: widthOfOut, height: calculatedHeight)
        }
        
        // 根据总页数决定是否显示pageControl
        if totalPages > 1 {
            pageControl.isHidden = false
            pageControl.numberOfPages = totalPages
            pageControl.currentPage = 0
        } else {
            pageControl.isHidden = true
        }
        
        // 重新加载外层CollectionView
        outerCollectionView.reloadData()
    }

    // MARK: - Action

    @objc private func tapExpandButton() {
//        introductionLabel.numberOfLines = 0
//        expendButton.isHidden = true
//        layoutIfNeeded()

        let vc = RoleIntroBrowseDialogController()
        vc.introduction = info?.introduction
        vc.imageUrl = info?.homeImageUrl
        vc.show()
    }

    class HomeAboutDataPanelItem: UIView {
        var countLabel: UILabel!
        var tipLabel: UILabel!
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupViews()
        }

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

        private func setupViews() {
            countLabel = {
                let v = UILabel()
                v.textColor = .text
                v.font = .t.tnml
                addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.top.equalToSuperview()
                }
                return v
            }()

            tipLabel = {
                let v = UILabel()
                v.textColor = .desc
                v.font = .t.tls
                addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.top.equalTo(countLabel.snp.bottom).offset(4)
                    make.bottom.equalToSuperview()
                }
                return v
            }()
        }
    }
}

class HomeAboutDataGiftGridCell: UICollectionViewCell {
    var block: UIView!
    var imageView: UIImageView!
    var countLabel: UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    private func setupViews() {
        // block, full width, height 88
        block = {
            let v = UIView()
            v.backgroundColor = .c.csnn
            v.layer.cornerRadius = 8
            v.layer.masksToBounds = true
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.height.equalTo(64)
            }
            return v
        }()

        imageView = {
            let v = UIImageView()
            v.contentMode = .scaleAspectFill
            v.layer.cornerRadius = 8
            v.layer.masksToBounds = true
            v.image = UIImage(named: "icon_32_diamond")
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 32, height: 32))
                make.center.equalToSuperview()
            }
            return v
        }()

        countLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tls
            v.text = "x 100"
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(block.snp.bottom).offset(4)
                // make.bottom.equalToSuperview()
            }
            return v
        }()
    }
    
    func config(_ data: AIRoleGiftReceivedList?){
        guard let gift = data else{return}
        
        countLabel.text = "x \(gift.getNum ?? 0)"
        // 设置礼物图片
        if let iconUrl = gift.icon, !iconUrl.isEmpty {
            imageView.loadImage(gift.icon, bgColor: nil)
        }
    }
}

// 新增：礼物页面Cell
class GiftPageCell: UICollectionViewCell {
    var innerCollectionView: UICollectionView!
    var giftsData: [AIRoleGiftReceivedList] = []
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let itemWidth = giftItemWidth//floor((UIScreen.width - 40 * 2 - 12 * 3) / 4.0) as CGFloat
        let itemHeight = giftItemHeight //CGFloat = itemWidth + 24
        layout.itemSize = .init(width: itemWidth, height: itemHeight)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = .init(top: 0, left: 16, bottom: 0, right: 16)
        
        innerCollectionView = {
            let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
            v.backgroundColor = .clear
            v.showsHorizontalScrollIndicator = false
            v.isScrollEnabled = false
            v.register(HomeAboutDataGiftGridCell.self, forCellWithReuseIdentifier: "HomeAboutDataGiftGridCell")
            v.dataSource = self
            v.delegate = self
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
    }
    
    func config(gifts: [AIRoleGiftReceivedList], pageIndex: Int) {
        self.giftsData = gifts
        innerCollectionView.reloadData()
    }
}

extension GiftPageCell: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return giftsData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeAboutDataGiftGridCell", for: indexPath) as! HomeAboutDataGiftGridCell
        
        let gift = giftsData[indexPath.item]
        cell.config(gift)
        
        return cell
    }
}

extension RoleHomeAboutView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == outerCollectionView {
            // 外层CollectionView：每页giftCountOnePage个礼物
            return max(1, (giftsData.count) / giftCountOnePage)
        }
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == outerCollectionView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GiftPageCell", for: indexPath) as! GiftPageCell
            
            // 计算当前页的礼物数据
            let startIndex = indexPath.item * giftCountOnePage
            let endIndex = min(Int(startIndex + giftCountOnePage), giftsData.count)
            let pageGifts = Array(giftsData[startIndex..<endIndex])
            
            cell.config(gifts: pageGifts, pageIndex: indexPath.item)
            return cell
        }
        return UICollectionViewCell()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == outerCollectionView {
            // 每行4个， 最多3行，根据giftsData.count计算高度， 每行间隔12
            let row = ceil(Double(giftsData.count) / 4.0)
            let height = giftItemHeight * CGFloat(row) + 12 * CGFloat(row - 1)
            return CGSize(width: UIScreen.width - 40 * 2, height: height)
        }
        return CGSize.zero
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == outerCollectionView {
            let pageWidth = scrollView.frame.width
            let currentPage = Int(round(scrollView.contentOffset.x / pageWidth))
            if currentPage != self.currentPage {
                self.currentPage = currentPage
                pageControl.currentPage = currentPage
            }
        }
    }
}
