//
//  LNFeedLikeView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/4.
//

import Foundation
import UIKit
import SnapKit


class LNFeedLikeView: UIView, LNFeedManagerNotify {
    let likeIc = UIImageView()
    let likeLabel = UILabel()
    
    var uiColor: UIColor = .text_4 {
        didSet {
            likeLabel.textColor = uiColor
            if !isLiked {
                likeIc.image = .icLikeEmpty.withTintColor(uiColor, renderingMode: .alwaysOriginal)
            }
        }
    }
    
    private var curId: String?
    private var isLiked = false
    private var likeCount: Int = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        likeIc.isUserInteractionEnabled = false
        likeIc.image = .icLikeEmpty.withTintColor(.text_4, renderingMode: .alwaysOriginal)
        addSubview(likeIc)
        likeIc.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.verticalEdges.equalToSuperview()
        }
        
        likeLabel.isUserInteractionEnabled = false
        likeLabel.font = .heading_h5
        likeLabel.textColor = .text_4
        addSubview(likeLabel)
        likeLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview()
            make.leading.equalTo(likeIc.snp.trailing).offset(2)
        }
        
        onTap { [weak self] in
            guard let self, let curId else { return }
            LNFeedManager.shared.likeFeed(id: curId)
        }
        
        LNEventDeliver.addObserver(self)
    }
    
    func update(id: String, liked: Bool, count: Int) {
        curId = id
        isLiked = liked
        likeCount = count
        
        _updateUI()
    }
    
    func onFeedLikedChanged(id: String, liked: Bool) {
        guard id == curId else { return }
        isLiked = liked
        likeCount += liked ? 1 : -1
        
        _updateUI()
    }
    
    private func _updateUI() {
        likeIc.image = isLiked ? .icLikeFilled : .icLikeEmpty.withTintColor(uiColor, renderingMode: .alwaysOriginal)
        likeLabel.text = likeCount == 0 ? .init(key: "A00301") : "\(likeCount.formattedAsShortNumber())"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
