//
//  YHMemberCenterHeaderView.swift
//  galaxy
//
//  Created by alexzzw on 2025/2/14.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import FSPagerView
import UIKit

class YHMemberCenterHeaderView: UIView {
    class BannerData {
        var level: YHMembershipLevel = .normal
        var levelString: String = ""
        
        var tips: String = ""
        var upgradeTitle: String = ""
        var showProgress: Bool = false
        var ratioString: String = ""
        var ratio: CGFloat = 0
        var showRatio: Bool = false
        var showTips: Bool = false

        init(level: YHMembershipLevel, levelString: String, tips: String, upgradeTitle: String, showProgress: Bool, ratioString: String, ratio: CGFloat, showRatio: Bool, showTips: Bool) {
            self.level = level
            self.levelString = levelString
            self.tips = tips
            self.upgradeTitle = upgradeTitle
            
            self.showProgress = showProgress
            self.ratioString = ratioString
            self.ratio = ratio
            self.showRatio = showRatio
            self.showTips = showTips
        }
    }

    static private let topMagin: CGFloat = 20
    static private let interitemSpacing: CGFloat = 12.0
    static var bannerWidth: CGFloat {
        let leftWidth: CGFloat = 12.0
        return KScreenWidth - interitemSpacing * 2 - leftWidth * 2.0
    }

    static var bannerHeight: CGFloat {
        let ratio: CGFloat = 194.0 / 327.0
        return bannerWidth * ratio
    }
    
    static var viewHeight: CGFloat {
        return bannerHeight + topMagin
    }
    
    var scrollToIndexEvent: ((YHMembershipLevel) -> Void)?
    var upgradeButtonEvent: ((_ level: YHMembershipLevel) -> Void)?
    var levelButtonEvent: ((_ level: YHMembershipLevel) -> Void)?

    lazy var bannerView: FSPagerView = {
        let view = FSPagerView()
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        view.isInfinite = false
        view.interitemSpacing = YHMemberCenterHeaderView.interitemSpacing
        view.register(YHMemberCenterHeaderBannerCell.self, forCellWithReuseIdentifier: "YHMemberCenterHeaderBannerCell")
        return view
    }()

    var datas: [BannerData] = []
    
    func updateDatas(_ memberCenterInfo: YHMemberCenterInfo) {
        datas = YHMembershipLevel.allCases.map({ level in
            var levelString = "您未达到该等级"
            var upgradeTitle = "去升级"
            var countFrom: Int = 0
            var countTo: Int = 0
            var tips: String = ""
            
            var showProgress: Bool = false
            var ratioString: String = ""
            var ratio: CGFloat = 0
            var showRatio: Bool = false
            var showTips: Bool = false
            
            switch level {
            case .normal:
                countFrom = 0
                countTo = 0
                if memberCenterInfo.currentLevel == level.rawValue {
                    levelString = "当前等级"
                    upgradeTitle = "已达成"
                    tips = "消费即升至黄金会员"
                    ratioString = "0"
                    ratio = 0
                    showRatio = true
                    showTips = true
                } else if memberCenterInfo.currentLevel > level.rawValue {
                    levelString = "您已高于该等级"
                    upgradeTitle = "已达成"
                    tips = "当前成长值"
                    ratioString = "\(memberCenterInfo.growthValue)"
                    ratio = 0
                    showRatio = false
                    showTips = false
                }
            case .gold:
                countFrom = 1
                countTo = 6001
                if memberCenterInfo.currentLevel < level.rawValue {
                    levelString = "您未达到该等级"
                    upgradeTitle = "去升级"
                    tips = "消费即升至黄金会员"
                    ratioString = "0"
                    ratio = 0
                    showRatio = true
                    showTips = true
                } else if memberCenterInfo.currentLevel == level.rawValue {
                    levelString = "当前等级"
                    upgradeTitle = "已达成"
                    tips = "距铂金会员还需\(countTo - memberCenterInfo.growthValue)成长值"
                    ratioString = "\(memberCenterInfo.growthValue)/\(countTo)"
                    let value = Double(memberCenterInfo.growthValue) / Double(countTo - 1)
                    ratio = value < 0 ? 0 : value
                    showProgress = true
                    showRatio = true
                    showTips = true
                } else if memberCenterInfo.currentLevel > level.rawValue {
                    levelString = "您已高于该等级"
                    upgradeTitle = "已达成"
                    tips = "当前成长值"
                    ratioString = "\(memberCenterInfo.growthValue)"
                    ratio = 0
                }
            case .platinum:
                countFrom = 6001
                countTo = 15001
                if memberCenterInfo.currentLevel < level.rawValue {
                    levelString = "您未达到该等级"
                    upgradeTitle = "去升级"
                    tips = "\(countFrom)成长值升至铂金会员"
                    ratioString = "\(countFrom)/(countTo)"
                    ratio = 0
                    showTips = true
                } else if memberCenterInfo.currentLevel == level.rawValue {
                    levelString = "当前等级"
                    upgradeTitle = "已达成"
                    tips = "距钻石会员还需\(countTo - memberCenterInfo.growthValue)成长值"
                    ratioString = "\(memberCenterInfo.growthValue)/\(countTo)"
                    let value = Double(memberCenterInfo.growthValue) / Double(countTo - 1)
                    ratio = value < 0 ? 0 : value
                    showProgress = true
                    showRatio = true
                    showTips = true
                } else if memberCenterInfo.currentLevel > level.rawValue {
                    levelString = "您已高于该等级"
                    upgradeTitle = "已达成"
                    tips = "当前成长值"
                    ratioString = "\(memberCenterInfo.growthValue)"
                    ratio = 0
                }
            case .diamond:
                countFrom = 15001
                countTo = Int.max
                if memberCenterInfo.currentLevel < level.rawValue {
                    levelString = "您未达到该等级"
                    upgradeTitle = "去升级"
                    tips = "\(countFrom)成长值升至钻石会员"
                    ratioString = "\(memberCenterInfo.growthValue)"
                    ratio = 0
                    showTips = true
                } else if memberCenterInfo.currentLevel == level.rawValue {
                    levelString = "当前等级"
                    upgradeTitle = "已达成"
                    tips = "当前成长值"
                    ratioString = "\(memberCenterInfo.growthValue)"
                    ratio = 0
                    showRatio = true
                    showTips = true
                }
            }
            
            return BannerData(level: level, levelString: levelString, tips: tips, upgradeTitle: upgradeTitle, showProgress: showProgress, ratioString: ratioString, ratio: ratio, showRatio: showRatio, showTips: showTips)
        })
        bannerView.reloadData()
//        if let index = datas.firstIndex(where: { data in
//            data.level.rawValue == memberCenterInfo.currentLevel
//        }) {
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
//                self.bannerView.scrollToItem(at: index, animated: false)
//                self.scrollToIndexEvent?(self.datas[index].level)
//            }
//        }
    }

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

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

    private func setupUI() {
        addSubview(bannerView)
        bannerView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(YHMemberCenterHeaderView.topMagin)
            make.bottom.left.right.equalToSuperview()
        }
        bannerView.itemSize = CGSize(width: YHMemberCenterHeaderView.bannerWidth, height: YHMemberCenterHeaderView.bannerHeight)
    }
}

extension YHMemberCenterHeaderView: FSPagerViewDataSource, FSPagerViewDelegate {
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return datas.count
    }

    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        guard datas.count > index else {
            return FSPagerViewCell()
        }
        if let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "YHMemberCenterHeaderBannerCell", at: index) as? YHMemberCenterHeaderBannerCell {
            let model = datas[index]
            cell.setupData(level: model.level, levelString: model.levelString, tips: model.tips, upgradeTitle: model.upgradeTitle, showProgress: model.showProgress, ratioString: model.ratioString, ratio: model.ratio, showRatio: model.showRatio, showTips: model.showTips)
            cell.levelButtonEvent = { [weak self] level in
                self?.levelButtonEvent?(level)
            }
            cell.upgradeButtonEvent = { [weak self] level in
                self?.upgradeButtonEvent?(level)
            }
            return cell
        }
        return FSPagerViewCell()
    }

    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        guard datas.count > targetIndex else {
            return
        }
        let level = datas[targetIndex].level
        scrollToIndexEvent?(level)
    }
}
