//
//  LNRoomGiftMessageCell.swift
//  Gami
//
//  Created by OneeChan on 2026/3/26.
//

import Foundation
import UIKit
import SnapKit


class LNRoomGiftMessageCell: UITableViewCell {
    private let contentLabel = UILabel()
    private let attachment = NSTextAttachment(image: .icGift)
    private var curItem: LNRoomGiftMessageItem?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupViews()
        
        attachment.bounds = .init(x: 0, y: -6.5, width: 22, height: 22)
    }
    
    func update(_ message: LNRoomGiftMessageItem) {
        curItem = message
        contentLabel.attributedText = buildContent(message)
        
        guard let iconURL = URL(string: message.giftIcon), !message.giftIcon.isEmpty else { return }
        SDWebImageManager.shared.loadImage(with: iconURL, progress: nil) { [weak self] image, _, error, _, _, _ in
            guard let self else { return }
            guard error == nil, let image else { return }
            guard self.curItem === message else { return }
            attachment.image = image
            contentLabel.attributedText = contentLabel.attributedText
        }
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        
        contentLabel.attributedText = nil
        curItem = nil
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomGiftMessageCell {
    private func buildContent(_ message: LNRoomGiftMessageItem, giftImage: UIImage = .icGift) -> NSAttributedString {
        let text = String(key: "B00130", message.senderName, message.receiverName, message.giftCount)
        let attr = NSMutableAttributedString(string: text, attributes: [
            .font: UIFont.heading_h5,
            .foregroundColor: UIColor.text_1
        ])
        
        let senderRange = (text as NSString).range(of: message.senderName)
        attr.addAttributes([
            .font: UIFont.heading_h5,
            .foregroundColor: UIColor.text_7
        ], range: senderRange)
        
        let receiverRange = (text as NSString).range(of: message.receiverName)
        attr.addAttributes([
            .font: UIFont.heading_h5,
            .foregroundColor: UIColor.text_7
        ], range: receiverRange)
        
        let countRange: NSRange? = if text.contains("x\(message.giftCount)") {
            (text as NSString).range(of: "x\(message.giftCount)")
        } else if text.contains("\(message.giftCount)x") {
            (text as NSString).range(of: "\(message.giftCount)x")
        } else {
            nil
        }
        if let countRange {
            attr.addAttributes([
                .font: UIFont.heading_h5,
                .foregroundColor: UIColor.text_7
            ], range: countRange)
        }
        
        let giftIconRange = (text as NSString).range(of: "{icon}")
        attr.replaceCharacters(in: giftIconRange, with: .init(attachment: attachment))
        
        return attr
    }
}

extension LNRoomGiftMessageCell {
    private func setupViews() {
        backgroundColor = .clear
        
        let container = UIView()
        container.backgroundColor = .fill.withAlphaComponent(0.12)
        container.layer.cornerRadius = 12
        container.onTap { [weak self] in
            guard let self else { return }
            guard let curItem else { return }
            let panel = LNRoomProfileCardPanel()
            panel.load(curItem.sender)
            panel.popup(self)
        }
        contentView.addSubview(container)
        container.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview().inset(8)
            make.leading.equalToSuperview()
            make.trailing.lessThanOrEqualToSuperview()
        }
        
        contentLabel.text = " "
        contentLabel.font = .heading_h5
        contentLabel.textColor = .text_1
        contentLabel.numberOfLines = 0
        container.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(10)
            make.verticalEdges.equalToSuperview().inset(8)
        }
    }
}
