//
//  LNIMConversationCell.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/3.
//

import Foundation
import UIKit
import SnapKit


class LNIMConversationCell: UITableViewCell {
    private let avatar = UIImageView()
    private let onlineView = LNOnlineView()
    private let titleLabel = UILabel()
    private let messageLabel = UILabel()
    private let timeLabel = UILabel()
    private let unreadLabel = UILabel()
    
    private var curItem: V2TIMConversation?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupViews()
        LNEventDeliver.addObserver(self)
    }
    
    func update(_ item: V2TIMConversation) {
        if item.userID?.isImOfficialId == true {
            if item.userID == LNIMOfficialIds.officialMessage.rawValue {
                avatar.image = .icImOfficial
                titleLabel.text = .init(key: "A00091")
            } else {
                avatar.image = .icImUnknownOfficial
                titleLabel.text = item.showName
            }
            titleLabel.textColor = .text_6
            onlineView.isHidden = true
        } else {
            titleLabel.text = item.displayName
            titleLabel.textColor = .text_5
            onlineView.isHidden = !LNIMManager.shared.isUserOnline(uid: item.userID ?? "")
        }
        messageLabel.attributedText = item.lastDisplayString
        if messageLabel.attributedText?.string.isEmpty != false,
           item.userID?.isImOfficialId == true {
            messageLabel.attributedText = NSAttributedString(string: .init(key: "A00092"))
        }
        timeLabel.text = item.lastDisplayDate?.tencentIMTimeDesc ?? ""
        
        if item.unreadCount > 0 {
            if item.unreadCount > 99 {
                unreadLabel.text = "99+"
            } else {
                unreadLabel.text = "\(item.unreadCount)"
            }
            unreadLabel.superview?.isHidden = false
        } else {
            unreadLabel.superview?.isHidden = true
        }
        curItem = item
        
        if let userInfo = item.extraInfo?.userInfo {
            avatar.showAvatar(userInfo.avatar)
        } else if let userId = item.userID, !userId.isImOfficialId {
            LNProfileManager.shared.getUserProfileDetail(uid: userId) { [weak self] info in
                guard let self else { return }
                guard let info else { return }
                item.extraInfo?.userInfo = info
                
                guard info.userNo == curItem?.userID else { return }
                
                avatar.showAvatar(info.avatar)
                titleLabel.text = item.displayName
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNIMConversationCell: LNIMManagerNotify {
    func onIMUserStatusChanged(uid: String, status: V2TIMUserStatusType) {
        guard uid == curItem?.userID else { return }
        
        onlineView.isHidden = status != .USER_STATUS_ONLINE
    }
}

extension LNIMConversationCell {
    private func setupViews() {
        backgroundColor = .clear
        
        avatar.layer.cornerRadius = 23
        avatar.clipsToBounds = true
        contentView.addSubview(avatar)
        avatar.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview().inset(9)
            make.width.height.equalTo(46)
        }
        
        contentView.addSubview(onlineView)
        onlineView.snp.makeConstraints { make in
            make.edges.equalTo(avatar).inset(-2)
        }
        
        let textView = buildTextView()
        contentView.addSubview(textView)
        
        let infoView = buildInfoView()
        contentView.addSubview(infoView)
        infoView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
            make.height.equalTo(textView)
        }
        
        textView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(avatar.snp.trailing).offset(10)
            make.trailing.equalTo(infoView.snp.leading).offset(-16)
        }
    }
    
    private func buildTextView() -> UIView {
        let container = UIView()
        
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.horizontalEdges.top.equalToSuperview()
        }
        
        messageLabel.font = .body_s
        messageLabel.textColor = .text_3
        container.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.horizontalEdges.bottom.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
        }
        
        return container
    }
    
    private func buildInfoView() -> UIView {
        let container = UIView()
        
        timeLabel.font = .body_xs
        timeLabel.textColor = .text_3
        timeLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        timeLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
        container.addSubview(timeLabel)
        timeLabel.snp.makeConstraints { make in
            make.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
        }
        
        let view = UIView()
        view.backgroundColor = .init(hex: "#F23051")
        view.layer.cornerRadius = 7
        container.addSubview(view)
        view.snp.makeConstraints { make in
            make.trailing.bottom.equalToSuperview()
            make.leading.greaterThanOrEqualToSuperview()
            make.height.equalTo(14)
        }
        
        unreadLabel.font = .body_xs
        unreadLabel.textColor = .text_1
        unreadLabel.textAlignment = .center
        view.addSubview(unreadLabel)
        unreadLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalToSuperview().inset(4)
        }
        
        return container
    }
}
