//
//  SessionListCell.swift

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

import UIKit
import SwipeCellKit
class SessionListCell: SwipeTableViewCell {
    
    var avatarView: CLImageView!
    var badge: BadgeView!
    
    var contentStackV : UIStackView!
    var namesStackH : UIStackView!
    var nameLabel: UILabel!
    var cardSwipeIcon: UIImageView!
    var relationTag: RelationshipTag!
    var contentLabel: UILabel! // May be ActiveLabel
    
    var rightItemsV:UIStackView!
    var timeLabel: UILabel!
    var heartbeatView: HeartBeatView!
    
    
    // -- Data
    var data : V2NIMConversation!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        selectionStyle = .none
        backgroundColor = .clear

        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews(){
        avatarView = {
            let v = CLImageView()
            contentView.addSubview(v)
            let wh = 48.0;
            v.layer.cornerRadius = wh * 0.5
            v.layer.masksToBounds = true
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.top.equalToSuperview().offset(16)
                make.bottom.equalToSuperview().offset(-16)
            }
            return v
        }()
        
        badge = {
            let v = BadgeView()
            v.showMax99 = true
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(avatarView)
                make.trailing.equalTo(avatarView).offset(4)
            }
            return v
        }()
        
        rightItemsV = {
            let v = UIStackView()
            v.axis = .vertical
            v.alignment = .trailing
            v.spacing = 6
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        timeLabel = {
            let v = UILabel()
            v.font = .t.tbs
            v.textColor = .c.ctsn
            v.setContentCompressionResistancePriority(UILayoutPriority(755), for: .horizontal)
            rightItemsV.addArrangedSubview(v)
            return v
        }()
        
        heartbeatView = {
            let v = HeartBeatView(viewSize: .small)
            rightItemsV.addArrangedSubview(v)
            return v
        }()
        
        contentStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 4
            v.alignment = .leading
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalTo(avatarView.snp.trailing).offset(12)
                make.trailing.lessThanOrEqualTo(rightItemsV.snp.leading).offset(-12)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        namesStackH = {
            let v = UIStackView()
            v.spacing = 4
            v.alignment = .center
            contentStackV.addArrangedSubview(v)
            return v
        }()
        
        nameLabel = {
            let v = UILabel()
            v.font = .t.tts
            v.textColor = .text
            v.setContentCompressionResistancePriority(UILayoutPriority(244), for: .horizontal)
            namesStackH.addArrangedSubview(v)
            return v
        }()
        
        cardSwipeIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "card_swipe_flag")
            namesStackH.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()

        relationTag = {
            let v = RelationshipTag()
            namesStackH.addArrangedSubview(v)
            return v
        }()

        contentLabel = {
            let v = UILabel()
            v.font = .t.tbs
            v.textColor = .text
            contentStackV.addArrangedSubview(v)
            return v
        }()
        
        
//        #warning("test")
//        testData()
    }
    
    private func testData(){
        avatarView.loadImage(UserCore.shared.user?.headImage)
        badge.badgeValue = 99
        nameLabel.text = "BBB CCC"
        relationTag.type = .friend
        contentLabel.text = "This is words"
        heartbeatView.content = "37.8℃"
        timeLabel.text = "22:28"
    }
    
    func config(_ conversation: V2NIMConversation){
        data = conversation
        
        if let serverExtension = conversation.serverExtension, let info = CodableHelper.decode(IMBaseRemoteInfo.self, from: serverExtension){
            print("💬conversationId:\(conversation.conversationId), extension:\(serverExtension)")
            dealServerExtension(info: info)
        }else{
            dealServerExtension(info: nil)
        }
        
        avatarView.loadImage(conversation.avatar)
        nameLabel.text = conversation.name
        badge.badgeValue = conversation.unreadCount
        if let lastMsgCreateTime = conversation.lastMessage?.messageRefer.createTime{
            timeLabel.text = Date.timerStyle(style: .IMCHAT, second: Int(lastMsgCreateTime))
        }else  {
            let updateTime = conversation.updateTime
            timeLabel.text =  Date.timerStyle(style: .IMCHAT, second: Int(updateTime))
        }
        
        
        contentLabel.text = contentWith(conversation: conversation)
    }
    
    /// 配置会话数据，支持搜索高亮
    /// - Parameters:
    ///   - conversation: 会话数据
    ///   - searchText: 搜索关键词，用于高亮显示
    func config(_ conversation: V2NIMConversation, searchText: String?) {
        data = conversation
        
        if let serverExtension = conversation.serverExtension, let info = CodableHelper.decode(IMBaseRemoteInfo.self, from: serverExtension){
            dlog("💬conversationId:\(conversation.conversationId), extension:\(serverExtension)")
            dealServerExtension(info: info)
        }else{
            dealServerExtension(info: nil)
        }
        
        avatarView.loadImage(conversation.avatar)
        
        // 设置名称，支持高亮显示
        if let searchText = searchText, !searchText.isEmpty, let name = conversation.name {
            nameLabel.attributedText = TextHighlightHelper.highlightText(name, searchText: searchText)
        } else {
            nameLabel.text = conversation.name
        }
        
        badge.badgeValue = conversation.unreadCount
        if let lastMsgCreateTime = conversation.lastMessage?.messageRefer.createTime{
            timeLabel.text = Date.timerStyle(style: .IMCHAT, second: Int(lastMsgCreateTime))
        }else  {
            let updateTime = conversation.updateTime
            timeLabel.text =  Date.timerStyle(style: .IMCHAT, second: Int(updateTime))
        }
        
        contentLabel.text = contentWith(conversation: conversation)
    }
    
    func dealServerExtension(info: IMBaseRemoteInfo?){
        let isShow = info?.isShow.trueOrNil
        
        heartbeatView.isHidden = false
        if let heartbeatVal = info?.heartbeatVal{
            heartbeatView.content = "\(heartbeatVal)"
        }else{
            heartbeatView.content = ""
        }
        
        if let level = info?.heartbeatLevel, isShow == true{
            relationTag.bind(level: level)
            relationTag.isHidden = false
        }else{
            relationTag.isHidden = true
        }
    }
    
    func contentWith(conversation: V2NIMConversation) -> String {
        guard let message = conversation.lastMessage else { return "No messages" }
        if message.messageType == .MESSAGE_TYPE_CUSTOM {
            return dealCustom(message: message)
        }
        if String.realEmpty(str: message.text) && message.serverExtension == nil && message.messageType == .MESSAGE_TYPE_TEXT {
            return dealCustom(message: message)
        }
        return dealNormal(message: message)
    }
}

// MARK: - Helper
extension SessionListCell{
    func dealCustom(message: V2NIMLastMessage) -> String {
//        let remoteInfo = IMRemoteUtil.dealRemoteInfo(message: <#T##V2NIMMessage?#>)
//        return "[Message]"
        if let raw = message.attachment?.raw, let attchment = CodableHelper.decode(IMCustomAttachment.self, from: raw){
            return attchment.getDisplayString()
        }
        return ""
    }
    
    func dealNormal(message: V2NIMLastMessage) -> String {
        var content = ""
        
        if String.realEmpty(str: content){
            content = message.text ?? ""
        }
        return content
    }
}
