//
//  YHCircleCollectionViewCell.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/24.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Kingfisher
import Lottie

class YHCircleCollectionViewCell: UICollectionViewCell {
    
    static let cellReuseIdentifier = "YHCircleCollectionViewCell"
    
    var listModel: YHDynamicItem? {
        didSet {
            updateUI()
        }
    }
    
    var onImageHeightChanged: (() -> Void)?
    var clickHeartEvent: (() -> Void)?
    
    // MARK: - UI Components
    
    lazy var titleImageView: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "plan_product_default"))
        imageV.contentMode = .scaleAspectFill
        imageV.isUserInteractionEnabled = true
        imageV.clipsToBounds = true
        return imageV
    }()
    
    private lazy var avatarImageView: UIImageView = {
        let iv = UIImageView()
        iv.layer.cornerRadius = 8
        iv.clipsToBounds = true
        iv.contentMode = .scaleAspectFill
        return iv
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.brandGrayColor6
        return label
    }()
    
    lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.text = ""
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_R(ofSize: 15)
        label.numberOfLines = 2
        label.lineBreakMode = .byTruncatingTail
        return label
    }()
    
    lazy var subHoldView: UIView = {
        let view = UIView()
        view.layer.backgroundColor = UIColor.white.cgColor
        view.layer.borderWidth = 0.6
        view.layer.borderColor = UIColor(red: 0.943, green: 0.952, blue: 0.969, alpha: 1).cgColor
        return view
    }()
    
    lazy var heartImageViewBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setImage(UIImage(named: "circle_grey_heart"), for: .normal)
        btn.setImage(UIImage(named: "circle_red_heart"), for: .selected)
        return btn
    }()
    
    lazy var numLable: UILabel = {
        let label = UILabel()
        label.text = ""
        label.textColor = UIColor.brandGrayColor6
        label.font = UIFont.PFSC_R(ofSize: 12)
        return label
    }()
    
    lazy var animationView: LottieAnimationView = {
        let view = LottieAnimationView(name: "shouye")
        view.isHidden = true
        return view
    }()
    
    // MARK: - Initialization
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    // MARK: - Setup UI
    
    private func setupUI() {
        contentView.clipsToBounds = true
        contentView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(210)
        }
        
        contentView.addSubview(subHoldView)
        subHoldView.snp.makeConstraints { make in
            make.top.equalTo(titleImageView.snp.bottom)
            make.bottom.left.right.equalToSuperview()
        }
        
        // 内容文本
        subHoldView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
        }
        
        // 头像
        subHoldView.addSubview(avatarImageView)
        // 昵称
        subHoldView.addSubview(nameLabel)
        subHoldView.addSubview(numLable)
        subHoldView.addSubview(animationView)
        subHoldView.addSubview(heartImageViewBtn)
        
        avatarImageView.setContentCompressionResistancePriority(.required, for: .horizontal)
        heartImageViewBtn.setContentCompressionResistancePriority(.required, for: .horizontal)
        numLable.setContentCompressionResistancePriority(.required, for: .horizontal)
        animationView.setContentCompressionResistancePriority(.required, for: .horizontal)
        nameLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        
        avatarImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.top.equalTo(contentLabel.snp.bottom).offset(12)
            make.width.height.equalTo(16)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarImageView.snp.right).offset(4)
            make.centerY.equalTo(avatarImageView)
            make.right.lessThanOrEqualTo(heartImageViewBtn.snp.left).offset(-8)
        }
        
        numLable.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(avatarImageView)
            make.height.equalTo(16)
        }
        
        animationView.snp.makeConstraints { make in
            make.right.equalTo(numLable.snp.left).offset(2.5)
            make.height.width.equalTo(24)
            make.centerY.equalTo(numLable).offset(-0.5)
        }
        
        heartImageViewBtn.snp.makeConstraints { make in
            make.right.equalTo(numLable.snp.left).offset(-2)
            make.height.width.equalTo(16)
            make.centerY.equalTo(numLable)
        }
        
        heartImageViewBtn.addTarget(self, action: #selector(clickHeart), for: .touchUpInside)
        heartImageViewBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
    }
    
    // MARK: - Actions
    @objc func clickHeart() {
        clickHeartEvent?()
    }
    
    // MARK: - Update UI
    
    func updateLikeState(isLike: Bool, currentModel: YHDynamicItem) {
        guard let model = listModel, currentModel.id == model.id else { return }
        self.numLable.text = model.like_count > 9999 ? "9999+" : model.like_count.string
        if isLike {
//            self.heartImageViewBtn.setImage(UIImage(named: ""), for: .selected)
//            self.heartImageViewBtn.setImage(UIImage(named: ""), for: .normal)
//            self.animationView.isHidden = false
//            self.animationView.loopMode = .playOnce
//            self.animationView.play { [weak self] _ in
//                guard let self = self else { return }
//                self.animationView.isHidden = true
//                self.heartImageViewBtn.setImage(UIImage(named: "circle_red_heart"), for: .normal)
//            }
            self.heartImageViewBtn.setImage(UIImage(named: "circle_red_heart"), for: .normal)
        } else {
            animationView.isHidden = true
            self.heartImageViewBtn.setImage(UIImage(named: "circle_grey_heart"), for: .normal)
        }
    }
    
    private func updateUI() {
        guard let model = listModel else { return }
        
        // 顶部图片
        titleImageView.snp.remakeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(model.img_height_use)
        }
        
        if let firstResource = model.firstImageResource, !firstResource.url.isEmpty, let url = URL(string: firstResource.url) {
            titleImageView.kf.setImage(with: url, placeholder: UIImage(named: "plan_product_default")) { _ in
//                switch result {
//                case let .success(value):
//                    DispatchQueue.global().async {
//                        var needRefreshHeight = false
//                        let size = value.image.size
//                        let scale = size.width > 0 ? Double(size.height / size.width) : 0.0
//                        if scale > 0 {
//                            let width = (KScreenWidth - 47) / 2
//                            let height = scale * width
//                            if height >= model.maxImageHeight, model.img_height_use >= model.maxImageHeight {
//                                return
//                            }
//                            if height <= model.minImageHeight, model.img_height_use <= model.minImageHeight {
//                                return
//                            }
//                            if abs(height - model.img_height_use) > 10 {
//                                model.calHeightParam(height)
//                                needRefreshHeight = true
//                            }
//                        }
//                        
//                        DispatchQueue.main.async {
//                            if needRefreshHeight {
//                                self.titleImageView.snp.remakeConstraints { make in
//                                    make.left.right.top.equalToSuperview()
//                                    make.height.equalTo(model.img_height_use)
//                                }
//                                self.onImageHeightChanged?()
//                            }
//                        }
//                    }
//                    
//                case .failure:
//                    printLog("kf setImage failed")
//                }
            }
        } else {
            titleImageView.image = UIImage(named: "plan_product_default")
        }
        
        // 用户信息
        nameLabel.text = model.nickname.isEmpty ? "-" : model.nickname
        
        // 头像
        if !model.avatar.isEmpty, let url = URL(string: model.avatar) {
            avatarImageView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
        } else {
            avatarImageView.image = UIImage(named: "people_head_default")
        }
        
        // 内容文本
        contentLabel.text = model.title
        contentLabel.snp.removeConstraints()
        contentLabel.snp.remakeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(model.textH)
        }
        numLable.text = model.like_count > 9999 ? "9999+" : model.like_count.string
        if model.like_self {
            heartImageViewBtn.setImage(UIImage(named: "circle_red_heart"), for: .normal)
        } else {
            heartImageViewBtn.setImage(UIImage(named: "circle_grey_heart"), for: .normal)
        }
    }
}
