//
//  SessionNavigationView.swift

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

import UIKit
import Lottie
import Combine
class SessionNavigationView: UIView {
    lazy var navigationView: NavigationView = {
        let view = NavigationView()
        return view
    }()

    var naviMoreButton: EPIconGhostButton!
    var moreBadge: BadgeView!
    var likeView : HeartLikeCountView!

    // -- One Avatar
    var newPeopleContainer: UIView!
    var avatar: CLImageView!
    var newPeopleStackV: UIStackView!
    var nameLabel: CLLabel!
    var likesLabel: CLLabel!
    var newPeopleAvatarTopButton: UIButton!

    // -- Two Avatars
    var heartLevelContainer: UIView!
    var aiAvatar: CLImageView!
    var mineAvatar: CLImageView!
    var hearIcon: UIImageView!
    var heartLottie: LottieAnimationView!
    var heartLevelLabel: UILabel!
    var heartTopButton: UIButton!
    var aiAvatarTopButton: UIButton!
    var mineAvatarTopButton: UIButton!

    // -- 额外区域
    var heartLevelTag: RelationshipTag!
    /// 升降级的NoticeView
    var upDownNoticeView : SessionHeartLevelNoticeView!

    var data: IMAIUserInfo?
    
    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 setupData() {
        refreshMoreButtonBadge()
    }

    private func setupEvent() {
        IMAIViewModel.shared.$heartbeatLevelUpString.sink {[weak self] string in
            guard let notice = string, notice.count > 0 else {return}
            self?.upDownNoticeView.showUnlocked(string: notice)
            self?.playUpgradeAnimationOnce()
        }.store(in: &cancellables)
        
        IMAIViewModel.shared.$heartbeatLevelDownString.sink {[weak self] string in
            guard let notice = string, notice.count > 0 else {return}
            self?.upDownNoticeView.showLose(string: notice)
            self?.playUpgradeAnimationOnce()
        }.store(in: &cancellables)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notiMoreButtonBadgeChanged), name: AppNotificationName.chatNaviMoreRedDotChanged.notificationName, object: nil)
    }

    // MARK: - Public

    func config(user: IMAIUserInfo?) {
        data = user
        guard let userInfo = user else {
            return
        }

        if userInfo.aiUserHeartbeatRelation?.heartbeatLevel != nil {
            // 有心动等级
            navigationView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(-40)
            }
            heartLevelContainer.isHidden = false
            newPeopleContainer.isHidden = true

            aiAvatar.loadImage(userInfo.aiUserHeartbeatRelation?.aiHeadImg)
            mineAvatar.loadImage(userInfo.aiUserHeartbeatRelation?.userHeadImg)

            heartLevelLabel.text = "\(userInfo.aiUserHeartbeatRelation?.heartbeatLevelNum ?? 0)"

            guard let level = userInfo.aiUserHeartbeatRelation?.heartbeatLevel, let heartBeatVal = userInfo.aiUserHeartbeatRelation?.heartbeatVal else {
                return
            }
            heartLevelTag.isHidden = false
            heartLevelTag.bind(level: level, heartBeatVal: heartBeatVal, isShow: userInfo.aiUserHeartbeatRelation?.isShow)
            
        } else {
            // 初始等级
            navigationView.snp.updateConstraints { make in
                make.bottom.equalToSuperview()
            }
            heartLevelContainer.isHidden = true
            newPeopleContainer.isHidden = false

            avatar.loadImage(userInfo.headImg)
            nameLabel.text = userInfo.nickname
            
            let number = NSNumber(value: userInfo.likedNum ?? 0)
//            #warning("test")
//            let number = NSNumber(value: 19320)
            
            let displayNumber = String.displayNumber(number, scale: 1)
            likesLabel.text = "\(displayNumber) likes"
        }
        
        likeView.isLike = userInfo.liked ?? false
    }
    
    func configOnlyHeartbeatVal(value: CGFloat?){
        guard value != nil else{return}
        
        guard let userInfo = data else {
            return
        }
        
        // let heartbeatVal = userInfo.aiUserHeartbeatRelation?.heartbeatVal
        guard let level = userInfo.aiUserHeartbeatRelation?.heartbeatLevel else {
            return
        }
        heartLevelTag.isHidden = false
        heartLevelTag.bind(level: level, heartBeatVal: value, isShow: userInfo.aiUserHeartbeatRelation?.isShow)
        
    }
    
    func playUpgradeAnimationOnce(){
        heartLottie.isHidden = false
        self.heartLottie.play {[weak self] completed in
            self?.heartLottie.isHidden = true
        }
    }
    
    // MARK: - Helper
    
    func refreshMoreButtonBadge(){
        let config = AppCache.fetchCache(key: CacheKey.chatRedBadgeConfig.rawValue, type: ChatSettingCacheConfig.self) ?? ChatSettingCacheConfig()
//        moreBadge.isHidden = config.chatBackgroundTapped && config.chatBubbleTapped
        moreBadge.isHidden = true
    }
    
    @objc private func notiMoreButtonBadgeChanged(){
        refreshMoreButtonBadge()
    }
    
    // MARK: - Actions, button点击在外部
    
    // MARK: - UI
    func addNavigationView() {
        addSubview(navigationView)

        navigationView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.height.equalTo(UIWindow.navBarTotalHeight)
            make.bottom.equalToSuperview().offset(-40)
        }
    }

    private func setupViews() {
        addNavigationView()
        navigationView.bgView.alpha = 0
        navigationView.backButton.setImage(UIImage(named: "role_back_white"), for: .normal)

        navigationView.paddingRightForRightStack = 2
        likeView = {
            let v = HeartLikeCountView(viewSize: .xl)
            v.purIconStyle()
            v.isHidden = true
            navigationView.rightStackH.addArrangedSubview(v)
            return v
        }()
        
        naviMoreButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .chatroomMore)
            navigationView.rightStackH.addArrangedSubview(v)
            v.setBackgroundImage(nil, for: .highlighted)
            v.setImage(UIImage(named: "role_chat_setting"), for: .normal)
            v.setImage(UIImage(named: "role_chat_setting"), for: .selected)
            v.setImage(UIImage(named: "role_chat_setting"), for: .highlighted)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 52, height: 44))
            }
            return v
        }()

        moreBadge = {
            let v = BadgeView()
            v.onlyShowPoint = true
            v.isHidden = true
            navigationView.addSubview(v)
            v.snp.makeConstraints { make in
//                make.top.equalTo(naviMoreButton)
//                make.trailing.equalTo(naviMoreButton)
                make.centerX.equalTo(naviMoreButton).offset(10)
                make.centerY.equalTo(naviMoreButton).offset(-6)
            }
            v.badgeValue = 1
            return v
        }()

        setupBasicContainer()
        setupHeartLevel()

        heartLevelTag = {
            let v = RelationshipTag()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(navigationView.snp.bottom).offset(4)
            }
            v.isHidden = true
            return v
        }()
        
        upDownNoticeView = {
            let v = SessionHeartLevelNoticeView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(heartLevelContainer.snp.bottom).offset(4)
                make.centerX.equalToSuperview()
            }
            return v
        }()
    }

    private func setupBasicContainer() {
        newPeopleContainer = {
            let v = UIView()
            navigationView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalTo(navigationView.titleLabel)
                make.height.equalTo(44)
                make.leading.equalTo(navigationView.leftStackH.snp.trailing)
                make.trailing.equalTo(navigationView.rightStackH.snp.leading)
            }
            return v
        }()

        avatar = {
            let v = CLImageView(frame: .zero)
            let wh = 40.0
            v.layer.cornerRadius = wh * 0.5
            v.layer.masksToBounds = true
            newPeopleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.leading.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        newPeopleAvatarTopButton = {
            let v = UIButton()
            newPeopleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        newPeopleStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.alignment = .leading
            newPeopleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalTo(avatar.snp.trailing).offset(8)
                make.trailing.lessThanOrEqualToSuperview()
            }
            return v
        }()

        nameLabel = {
            let v = CLLabel()
            v.font = .t.ttm
            newPeopleStackV.addArrangedSubview(v)
            return v
        }()

        likesLabel = {
            let v = CLLabel()
            v.font = .t.tls
            newPeopleStackV.addArrangedSubview(v)
            return v
        }()
    }

    private func setupHeartLevel() {
        heartLevelContainer = {
            let v = UIView()
            navigationView.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalTo(navigationView.titleLabel)
                make.height.equalTo(44)
            }
            return v
        }()
        
        heartLevelContainer.isHidden = true
        
        aiAvatar = {
            let v = CLImageView(frame: .zero)
            let wh = 40.0
            v.layer.cornerRadius = wh * 0.5
            v.layer.masksToBounds = true
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.leading.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()
        mineAvatar = {
            let v = CLImageView(frame: .zero)
            let wh = 40.0
            v.layer.cornerRadius = wh * 0.5
            v.layer.masksToBounds = true
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.trailing.equalToSuperview()
                make.leading.equalTo(aiAvatar.snp.trailing).offset(24)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        hearIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "chat_level_heart")
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 44, height: 44))
                make.center.equalToSuperview()
            }
            return v
        }()
        
        heartLottie = {
            let animation = LottieAnimation.named("heartbeat_pink")
            let animationView = LottieAnimationView(animation: animation)

            animationView.contentMode = .scaleAspectFit
            animationView.loopMode = .playOnce
            animationView.backgroundBehavior = .pauseAndRestore
            animationView.backgroundColor = .clear
            animationView.size = CGSize(width: 44, height: 44)
            heartLevelContainer.addSubview(animationView)
            animationView.snp.makeConstraints { make in
                make.center.equalTo(hearIcon)
                make.size.equalTo(CGSize(width: 240, height: 210))
            }
            animationView.isHidden = true
            return animationView
        }()
        
        heartLevelLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tnmm
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalTo(hearIcon)
            }
            return v
        }()
        
        aiAvatarTopButton = {
            let v = UIButton()
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalTo(aiAvatar)
            }
            return v
        }()
        
        mineAvatarTopButton = {
            let v = UIButton()
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalTo(mineAvatar)
            }
            return v
        }()

        heartTopButton = {
            let v = UIButton()
            heartLevelContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalTo(hearIcon)
            }
            return v
        }()
    }
    
}
