//
//  GiftGridSendView.swift

//
//  Created by Leon on 2025/8/22.
//

import UIKit
import Combine

protocol GiftGridSendViewDelegate : AnyObject{
    func giftSend(giftId: Int, gift: GiftDictModel, num: Int)
    func giftGoHeartbeatPage()
    func giftGoVIPCenter()
    /// 外部去选择数量
    func giftNumPick(num: Int)
}

class GiftGridSendView: UIView {
    weak var delegate : GiftGridSendViewDelegate?
    
    var bgView: UIView!
    var cv: UICollectionView!
    var layout = UICollectionViewFlowLayout()

    var bottomView: UIView!
    var coinLabel: CLIconLabel!
    
    var sendContainer: UIView!
    var operateButton: StyleButton!

    var countContainer: UIView!
    var countLabel: CLLabel!
    var selectCountButton: UIButton!
    var countImg : UIImageView!
    // -- Data
    
    /// @Requered
    @Published var targetHeartbeatValue: CGFloat?
    
    var gifts: [GiftDictModel] = [GiftDictModel]()
    @Published var selectGiftId: Int?
    @Published var num: Int = 1
    
    var selectGift : GiftDictModel?
    private var cancellables = Set<AnyCancellable>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

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

    private func setupViews() {
        backgroundColor = .c.csbn
        
        bgView = {
            let v = UIView()
            v.backgroundColor = backgroundColor
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview().offset(UIWindow.safeAreaBottom + 16)
            }
            return v
        }()
        
        bottomView = {
            let v = UIView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(80)
                make.leading.trailing.equalToSuperview()
                make.bottom.equalToSuperview()//.offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            return v
        }()
        
        cv = {
            let itemsInRow = 3.0
            let width = floor((UIScreen.width - 24.0 * 2) * (1 / itemsInRow))
            let height = 88.0 + 52.0// 140.0 //width + 24
            layout.scrollDirection = .vertical
            layout.itemSize = CGSize(width: width, height: height)
            layout.minimumLineSpacing = 16
            layout.minimumInteritemSpacing = 0
            layout.sectionInset = UIEdgeInsets(top: 16, left: 24, bottom:16, right: 24)

            cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
            cv.backgroundColor = .clear
            cv.showsHorizontalScrollIndicator = false
            cv.delegate = self
            cv.dataSource = self
            cv.contentInsetAdjustmentBehavior = .never
            cv.register(IMGiftGridCell.self, forCellWithReuseIdentifier: "IMGiftGridCell")
            addSubview(cv)
            cv.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalTo(bottomView.snp.top)
                make.height.equalTo(200)
            }
            return cv
        }()

        coinLabel = {
            let label = CLIconLabel()
            label.iconImageView.image = UIImage(named: "icon_16_diamond")
            label.contentLabel.font = .t.tlm
            bottomView.addSubview(label)
            label.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(24)
            }
            return label
        }()

        sendContainer = {
            let v = UIView()
            bottomView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-24)
                make.height.equalTo(48)
            }
            return v
        }()

        operateButton = {
            let v = StyleButton()
            v.addTarget(self, action: #selector(tapOperateButton), for: .touchUpInside)
            v.primary(size: .large)
            sendContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()

        do {
            countContainer = {
                let v = UIView()
                sendContainer.addSubview(v)
                v.layer.borderWidth = 1
                v.layer.borderColor = UIColor.c.con.cgColor
                v.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
                v.cornerRadius = 24
                v.snp.makeConstraints { make in
                    make.leading.equalToSuperview()
                    make.bottom.top.equalToSuperview()
                    make.trailing.equalTo(operateButton.snp.leading).offset(24)
                }
                return v
            }()
            
            let downArrow = {
                let v = UIImageView()
                v.image = MWIconFont.image(fromIcon: .arrowDownFill, size: CGSize(width: 16, height: 16), color: .c.ctsn)
                countContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerY.equalToSuperview()
                    make.trailing.equalToSuperview().offset(-24-12)
                    make.size.equalTo(CGSize(width: 16, height: 16))
                }
                return v
            }()
            countImg = downArrow

            countLabel = {
                let v = CLLabel()
                v.font = .t.tll
                countContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerY.equalToSuperview()
                    make.trailing.equalTo(downArrow.snp.leading).offset(-12)
                    make.leading.equalToSuperview().offset(32)
                }
                return v
            }()

            selectCountButton = {
                let v = UIButton()
                v.addTarget(self, action: #selector(tapSelectCountButton), for: .touchUpInside)
                countContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                return v
            }()
        }
        sendContainer.bringSubviewToFront(operateButton)

        operateButton.setTitle("Gift", for: .normal)
    }

    private func setupData() {
        //coinLabel.contentLabel.text = "123"
        countLabel.text = "1"
        
        gifts = AppDictManager.shared.gifts ?? []
        if let gift = gifts.first, let firstGiftId = gift.id{
            selectGiftId = firstGiftId
            selectGift = gift
            cv.reloadData()
        }
        
    }

    private func setupEvent() {
        
        $selectGiftId.sink {[weak self] giftId in
            self?.operateButton.isEnabled = (giftId ?? 0) > 0
            self?.cv.reloadData()
            
            if let select = self?.selectGift{
                // 检查选择的礼物是否需要更高等级
                self?.updateOperateButtonTitle(for: select)
            }
        }.store(in: &cancellables)
        
        $targetHeartbeatValue.sink {[weak self] val in
            self?.selectGiftId = self?.selectGiftId
        }.store(in: &cancellables)
        
        IMAIViewModel.shared.$aiIMInfo.sink {[weak self] result in
            if let val = result?.aiUserHeartbeatRelation?.heartbeatVal{
                self?.targetHeartbeatValue = val
            }
        }.store(in: &cancellables)
        
        $num.sink {[weak self] number in
            self?.countLabel.text = "\(number)"
        }.store(in: &cancellables)
        
        WalletCore.shared.$balance.sink {[weak self] balance in
            if let priceLabel = self?.coinLabel {
                priceLabel.contentLabel.text = balance.displayBalance()
            }
        }.store(in: &cancellables)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifyVIPChanged(_:)), name: AppNotificationName.vipStateChange.notificationName, object: nil)
    }
    
    @objc private func notifyVIPChanged(_ noti: Notification){
        self.selectGiftId = selectGiftId
    }
    
    // MARK: Public
    
    func reset(){
        num = 1
        resetSelectGift()
    }
    
    // MARK: - Helper
    private func resetSelectGift(){
        if let gift = gifts.first, let firstGiftId = gift.id{
            selectGiftId = firstGiftId
            selectGift = gift
            cv.reloadData()
        }
    }

    // MARK: Action

    @objc private func tapOperateButton() {
        guard let id = selectGiftId else{
            return
        }
        
        // 获取当前选择的礼物
        guard let gift = gifts.first(where: { $0.id == id }) else {
            return
        }
        
        // 检查礼物的startVal是否大于目标用户的心动值
        if let startVal = gift.startVal,
           let targetValue = targetHeartbeatValue,
           CGFloat(startVal) > targetValue {
            // 如果礼物的startVal大于目标用户的心动值，跳转到心动页面
            delegate?.giftGoHeartbeatPage()
        } else if gift.isMemberGift.boolValue && UserCore.shared.user?.isMember.boolValue == false{
            delegate?.giftGoVIPCenter()
        }
        else {
            // 否则正常发送礼物
            delegate?.giftSend(giftId: id,gift: gift, num: num)
        }
    }

    @objc private func tapSelectCountButton() {
        delegate?.giftNumPick(num: num)
    }
}

extension GiftGridSendView: UICollectionViewDelegate, UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return gifts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "IMGiftGridCell", for: indexPath) as! IMGiftGridCell
        let data = gifts[indexPath.item]
        cell.config(data)
        cell.setupSelected(selectedId: selectGiftId)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = gifts[indexPath.item]
        selectGift = data
        selectGiftId = data.id
    }
    
    // MARK: Private Helper
    
    private func updateOperateButtonTitle(for gift: GiftDictModel) {
        // 检查礼物的startVal是否大于目标用户的心动值
        if let startVal = gift.startVal,
           let targetValue = targetHeartbeatValue,
           CGFloat(startVal) > targetValue {
            countContainer.isHidden = true
            operateButton.primary(size: .large)
            // 如果礼物的startVal大于目标用户的心动值，显示解锁提示
            var buttonTitle = "Unlock"
            if let heartbeatLevel = gift.heartbeatLevel {
                let message = "\(heartbeatLevel.localizedText) unlock"
                buttonTitle = message
            }
            let aStr = NSAttributedString.getIconTitleAttributeByWords(words: buttonTitle, textFont: .t.tll,textColor: .white)
            operateButton.setAttributedTitle(aStr, for: .normal)
        } else if gift.isMemberGift.boolValue && UserCore.shared.user?.isMember.boolValue == false{
            // VIP unlock
            countContainer.isHidden = true
            // ...
            operateButton.vip(size: .large)
            let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Member unlock", icon:.iconVip, textFont: .t.tll)
            operateButton.setAttributedTitle(aStr, for: .normal)
        }
        else {
            countContainer.isHidden = false
            operateButton.primary(size: .large)
            
            let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Gift", textFont: .t.tll,textColor: .white)
            operateButton.setAttributedTitle(aStr, for: .normal)
        }
    }
}
