//
//  FrinendsListCell.swift

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

import UIKit

protocol FriendsListCellDelegate: AnyObject{
    func friendsCellTapChat(aiId: Int)
}

class FriendsListCell: UITableViewCell {
    weak var delegate : FriendsListCellDelegate?
    
    var avatarView: CLImageView!
    var badge: BadgeView!

    var chatEntrance: UIButton!

    var contentStackV: UIStackView!

    var namesStackH: UIStackView!
    var nameLabel: UILabel!
    var relationTag: RelationshipTag!
    var subContentH: UIStackView!
    var heartbeatView: HeartBeatView!
    var line: UIView!
    var subLabel: UILabel!

    var data: RelationFriend?

    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()
        setupData()
        setupEvent()
    }

    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
        }()

        chatEntrance = {
            let v = UIButton()
            v.layer.cornerRadius = 16
            v.layer.masksToBounds = true
            v.backgroundColor = .c.cpn
            v.contentMode = .center
            v.addTarget(self, action: #selector(tapChat), for: .touchUpInside)
            let img = MWIconFont.image(fromIcon: .chat, size: CGSize(width: 16, height: 16), color: .white)
            v.setImage(img, for: .normal)
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 48, height: 32))
                make.trailing.equalToSuperview().offset(-24)
                make.centerY.equalToSuperview()
            }
            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.centerY.equalToSuperview()
                make.trailing.lessThanOrEqualTo(chatEntrance.snp.leading).offset(-8)
            }
            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
            namesStackH.addArrangedSubview(v)
            return v
        }()

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

        subContentH = {
            let v = UIStackView()
            contentStackV.addArrangedSubview(v)
            v.spacing = 8
            v.alignment = .center
            return v
        }()

        heartbeatView = {
            let v = HeartBeatView(viewSize: .small)
            subContentH.addArrangedSubview(v)
            return v
        }()

        line = {
            let v = UIView()
            v.backgroundColor = .c.con
            subContentH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 1, height: 12))
            }
            return v
        }()

        subLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tbs
            subContentH.addArrangedSubview(v)
            return v
        }()
    }

    private func setupData() {
//        #warning("test")
//        testData()
    }

    private func testData() {
        relationTag.type = .friend
        nameLabel.text = "Lee"
        heartbeatView.content = "37.8℃"
        subLabel.text = "27 · Sensual · Romantic"
        avatarView.loadImage(UserCore.shared.user?.headImage)
    }

    private func setupEvent() {
    }

    // MARK: - Public

    func config(_ data: RelationFriend?) {
        self.data = data
        guard let theData = data else {
            return
        }

        relationTag.bind(level: theData.heartbeatLevel)
        nameLabel.text = theData.nickname
        if let heartbeatVal = theData.heartbeatVal {
            heartbeatView.isHidden = false
            heartbeatView.content = "\(heartbeatVal)"
        } else {
            heartbeatView.isHidden = true
            heartbeatView.content = ""
        }
        
        if let heartBeatLevel = theData.heartbeatLevel , theData.isShow.boolValue{
            relationTag.isHidden = false
            relationTag.bind(level: heartBeatLevel)
        }else{
            relationTag.isHidden = true
        }
            

        var showsArray = [String]()
        if let birthday = theData.birthday {
            let date = Date.dateFromMilliseconds(birthday)
            let age = Date().years(from: date)
            showsArray.append("\(age)")
        }

        if let characterName = theData.characterName {
            showsArray.append(characterName)
        }

        if let tagName = theData.tagName {
            showsArray.append(tagName)
        }

        if showsArray.count > 0 {
            subLabel.text = showsArray.joined(separator: " · ")
        } else {
            subLabel.text = ""
        }

        avatarView.loadImage(theData.headImg)
        // ...
    }
    
    /// 配置好友数据，支持搜索高亮
    /// - Parameters:
    ///   - data: 好友数据
    ///   - searchText: 搜索关键词，用于高亮显示
    func config(_ data: RelationFriend?, searchText: String?) {
        self.data = data
        guard let theData = data else {
            return
        }

        relationTag.bind(level: theData.heartbeatLevel)
        
        // 设置名称，支持高亮显示
        if let searchText = searchText, !searchText.isEmpty, let nickname = theData.nickname {
            nameLabel.attributedText = TextHighlightHelper.highlightText(nickname, searchText: searchText)
        } else {
            nameLabel.text = theData.nickname
        }
        
        if let heartbeatVal = theData.heartbeatVal {
            heartbeatView.isHidden = false
            heartbeatView.content = "\(heartbeatVal)"
        } else {
            heartbeatView.isHidden = true
            heartbeatView.content = ""
        }
        
        if let heartBeatLevel = theData.heartbeatLevel , theData.isShow.boolValue{
            relationTag.bind(level: heartBeatLevel)
        }else{
            relationTag.isHidden = true
        }
            

        var showsArray = [String]()
        if let birthday = theData.birthday {
            let date = Date.dateFromMilliseconds(birthday)
            let age = Date().years(from: date)
            showsArray.append("\(age)")
        }

        if let characterName = theData.characterName {
            showsArray.append(characterName)
        }

        if let tagName = theData.tagName {
            showsArray.append(tagName)
        }

        if showsArray.count > 0 {
            subLabel.text = showsArray.joined(separator: " · ")
        } else {
            subLabel.text = ""
        }

        avatarView.loadImage(theData.headImg)
        // ...
    }

    // MARK: - Action

    @objc private func tapChat() {
        guard let aiId = self.data?.aiId else {
            return
        }
        delegate?.friendsCellTapChat(aiId: Int(aiId))
    }
}
