//
//  ChatBubbleGridView.swift

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

import UIKit
import Combine

class ChatBubbleGridView: CLContainer {
    var bottomButton: StyleButton!
    var cv: UICollectionView!
    var layout = UICollectionViewFlowLayout()
    var titleView: TitleView!
    var headHeight: CGFloat = 60
    
    var datas = [IMChatBubble]()
    
    var inUseCode: String?
    @Published var selectCode : String?
    
    @Published var selectBubble: IMChatBubble?
    
    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() {
        bottomButton = {
            let v = StyleButton()
            v.primary(size: .large)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            return v
        }()

        cv = {
            let width = floor((UIScreen.width - 24 * 2 - 16) * 0.5)
            let height = 148.0
            layout.scrollDirection = .vertical
            layout.itemSize = CGSize(width: width, height: height)
            layout.minimumLineSpacing = 16
            layout.minimumInteritemSpacing = 16
            layout.sectionInset = UIEdgeInsets(top: 12, left: 24, bottom: UIWindow.safeAreaBottom, 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(ChatBubbleGridCell.self, forCellWithReuseIdentifier: "ChatBubbleGridCell")
            cv.register(UICollectionReusableView.self,
                        forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                        withReuseIdentifier: "UICollectionReusableView")
            addSubview(cv)
            cv.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
                make.bottom.equalTo(bottomButton.snp.top).offset(-16)
            }
            return cv
        }()

        titleView = {
            let v = TitleView()
            v.title = "Chat Bubble"
            return v
        }()
        titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: titleView.preCalculateHeight())
        bottomButton.setTitle("Use", for: .normal)
    }

    private func setupData() {
    }

    private func setupEvent() {
        $selectCode.sink {[weak self] str in
            self?.cv.reloadData()
            self?.bottomButton.isEnabled = !str.isNilOrEmpty
            
            if str == self?.inUseCode ?? ""{ // 已选中的，按钮置灰
                self?.bottomButton.isEnabled = false
            }
            
            for per in self?.datas ?? []{
                if per.code ?? "" == str{
                    self?.selectBubble = per
                    break
                }
            }
        }.store(in: &cancellables)
        
        $selectBubble.sink {[weak self] bubble in
            guard let theBubble = bubble else{return}
            switch theBubble.unlockType{
            case .none:
                self?.bottomButton.primary(size: .large)
                let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Use", textFont: .t.tll,textColor: .white)
                self?.bottomButton.setAttributedTitle(aStr, for: .normal)
            case .member:
                if UserCore.shared.user?.isMember ?? false{
                    self?.bottomButton.primary(size: .large)
                    let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Use", textFont: .t.tll,textColor: .white)
                    self?.bottomButton.setAttributedTitle(aStr, for: .normal)
                }else{
                    self?.bottomButton.vip(size: .large)
                    let aStr = StyleButton.getVIPBlackTitleByWords(words: "Member unlock")
                    self?.bottomButton.setAttributedTitle(aStr, for: .normal)
                }
            case .heartbeatLevel:
                if let level = IMAIViewModel.shared.aiIMInfo?.aiUserHeartbeatRelation?.heartbeatLevel, level.isGreaterOrEqual(to: theBubble.unlockHeartbeatLevel ?? .level1){
                    // 等级够了
                    self?.bottomButton.primary(size: .large)
                    let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Use", textFont: .t.tll,textColor: .white)
                    self?.bottomButton.setAttributedTitle(aStr, for: .normal)
                }else{
                    self?.bottomButton.primary(size: .large)
                    let words = theBubble.unlockHeartbeatLevel?.localizedText ?? "-"
                    let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Heartbeat \(words) unlock", iconImage: UIImage(named: "icon_pink_heart"), textFont: .t.tll,textColor: .white)
                    self?.bottomButton.setAttributedTitle(aStr, for: .normal)
                }
            }
        }.store(in: &cancellables)
    }
    
    func config(_ datas: [IMChatBubble]?, selectCode: String?){
        self.datas = datas ?? []
        inUseCode = selectCode
        self.selectCode = selectCode
        cv.reloadData()
    }
}

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChatBubbleGridCell", for: indexPath) as! ChatBubbleGridCell
        let data = datas[indexPath.row]
        cell.config(data)
        cell.configInUse(inUseCode: inUseCode)
        cell.configSelectCode(selectCode)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = datas[indexPath.row]
//        if data.canUseTheBubble(){
            selectCode = data.code
//        }
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "UICollectionReusableView",
                for: indexPath
            )
            if titleView.superview == nil || titleView.superview != header {
                titleView.removeFromSuperview()
            }

            header.addSubview(titleView)
            titleView.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                // make.bottom.equalToSuperview()
            }

            return header
        }
        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: UIScreen.width, height: headHeight)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, alphaViews: [navigationView?.titleLabel])
    }
}

class ChatBubbleGridCell: UICollectionViewCell {
    var block: UIView!
    
    var imageView: UIImageView!
    var wordsLabel: CLLabel!
    var defaultFlag: EPTagLabel!
    
    var inUseIcon : UIImageView!
    var lockIcon: EPIconTertiaryDarkButton!
    
    var nameStackH : UIStackView!
    var nameLeadingIcon : UIImageView!
    var nameLabel: ColorLabel!
    
    var data: IMChatBubble?

    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() {
        block = {
            let v = UIView()
            v.cornerRadius = 16
            v.backgroundColor = .c.csen
            v.layer.borderColor = UIColor.c.cpn.cgColor
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.top.equalToSuperview()
                make.height.equalTo(120)
            }
            return v
        }()
        
        imageView = {
            let v = UIImageView()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.height.equalTo(44)
            }
            return v
        }()
        
        defaultFlag = {
            let v = EPTagLabel(style: .blackOnColor)
            v.text = "Default"
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(8)
                make.leading.equalToSuperview().offset(8)
            }
            v.isHidden = true
            return v
        }()
        
        wordsLabel = {
            let v = CLLabel()
            v.font = .t.tbm
            imageView.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(imageView).offset(12)
                make.bottom.equalToSuperview().offset(-12)
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
            }
            return v
        }()
        
        inUseIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "checkmark_tick")
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 20, height: 20))
                make.top.equalToSuperview().offset(10)
                make.trailing.equalToSuperview().offset(-8)
            }
            v.isHidden = true
            return v
        }()

        lockIcon = {
            let v = EPIconTertiaryDarkButton(radius: .rectangle, iconSize: .small, iconCode: .iconPrivateBorder)
            v.isUserInteractionEnabled = false
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(8)
                make.trailing.equalToSuperview().offset(-8)
            }
            return v
        }()
        
        nameStackH = {
            let v = UIStackView()
            v.spacing = 4
            v.alignment = .center
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(block.snp.bottom).offset(8)
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
            }
            return v
        }()
        
        nameLeadingIcon = {
            let v = UIImageView()
            nameStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 12, height: 12))
            }
            v.isHidden = true
            return v
        }()

        nameLabel = {
            let v = ColorLabel()
            v.font = .t.tlm
            v.textColor = .white
            v.adjustsFontSizeToFitWidth = true
            v.minimumScaleFactor = 0.5
            contentView.addSubview(v)
            nameStackH.addArrangedSubview(v)
            return v
        }()

        // setupSelected(selected: true)
        // nameLabel.text = "Default"
        wordsLabel.text = "Hi"
    }

    private func setupData() {
    }

    private func setupEvent() {
    }
    
    // MARK: - Public
    func configInUse(inUseCode:String?){
        guard let theDataCode = data?.code, let theUsedCode = inUseCode, theUsedCode == theDataCode else{
            inUseIcon.isHidden = true
            return
        }
        inUseIcon.isHidden = false
    }

    func config(_ data: IMChatBubble?){
        self.data = data
        
        guard let theData = data else{return}
        
        nameLabel.text = theData.name
        nameLeadingIcon.isHidden = true
        if let type = theData.unlockType{
            switch type {
            case .member:
                nameLeadingIcon.isHidden = false
                nameLeadingIcon.image = UIImage(named: "vip_flag_16")
                nameLabel.applyGradient(.vip)
            case .heartbeatLevel:
                nameLeadingIcon.isHidden = false
                nameLeadingIcon.image = UIImage(named: "heart_little_Liked_12")
                nameLabel.clearGradient()
            }
        }else{
            nameLabel.clearGradient()
        }
        
        
        lockIcon.isHidden = theData.isUnlock.boolValue || theData.isDefault.boolValue
        
        defaultFlag.isHidden = !theData.isDefault.boolValue
        
         let imgUrl = theData.webImgUrl
//        let imgUrl = "https://hhb.crushlevel.ai/static/chatBubble/chat_bubble_1.png"
        imageView.loadImage(imgUrl, completionBlock:{[weak self] result in
            switch result {
            case let .success(imageResult):
                let image = imageResult.image
                let scaleImage = image.scaled(toHeight: 44)
                let stretchedImage = scaleImage!.stretchableImage(horizontalRatio: 0.5, verticalRatio: 0.5)
                self?.imageView.image = stretchedImage
            case .failure:
                return
            }
        })
    }
    
    func configSelectCode(_ code: String?){
        if let theCode = code, let dataCode = data?.code, theCode == dataCode {
            setupSelected(selected: true)
        }else{
            setupSelected(selected: false)
        }
    }
    
    // MARK: - Helper
    
    private func setupSelected(selected: Bool) {
        block.layer.borderWidth = selected ? 2 : 0
    }
    
}
