//
//  TransactionViewCell.swift
//  B24PaymentSdk
//
//  Created by visal ny on 24/12/24.
//

import UIKit

class TransactionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var container: UIView!
    
    @IBOutlet weak var line: UIView!
    
    @IBOutlet weak var bgLogo: UIView!
    
    @IBOutlet weak var logo: UIImageView!
    
    @IBOutlet weak var tranDateLabel: UILabel!
    
    @IBOutlet weak var amountLabel: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    
    private var logoConstraints: [NSLayoutConstraint] = []
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupBgLogoStyle()
    }
    
    private func setupBgLogoStyle() {
        // bgLogo has fixed size of 50x50 in XIB, update to 40x40 programmatically
        bgLogo.constraints.forEach { constraint in
            if constraint.firstAttribute == .width || constraint.firstAttribute == .height {
                constraint.constant = 40
            }
        }
        bgLogo.layer.cornerRadius = 20
        bgLogo.clipsToBounds = true
    }

    func setLogoFill(_ fill: Bool) {
        // Remove all existing constraints related to logo in bgLogo
        bgLogo.constraints.forEach { constraint in
            if constraint.firstItem === logo || constraint.secondItem === logo {
                bgLogo.removeConstraint(constraint)
            }
        }
        
        // Remove constraints on the logo itself
        logo.removeConstraints(logo.constraints)
        
        NSLayoutConstraint.deactivate(logoConstraints)
        logoConstraints.removeAll()
        
        logo.translatesAutoresizingMaskIntoConstraints = false
        
        if fill {
            logoConstraints = [
                logo.topAnchor.constraint(equalTo: bgLogo.topAnchor),
                logo.bottomAnchor.constraint(equalTo: bgLogo.bottomAnchor),
                logo.leadingAnchor.constraint(equalTo: bgLogo.leadingAnchor),
                logo.trailingAnchor.constraint(equalTo: bgLogo.trailingAnchor)
            ]
            logo.contentMode = .scaleAspectFill
        } else {
            logoConstraints = [
                logo.centerXAnchor.constraint(equalTo: bgLogo.centerXAnchor),
                logo.centerYAnchor.constraint(equalTo: bgLogo.centerYAnchor),
                logo.widthAnchor.constraint(equalTo: bgLogo.widthAnchor, multiplier: 0.4),
                logo.heightAnchor.constraint(equalTo: bgLogo.heightAnchor, multiplier: 0.4)
            ]
            logo.contentMode = .scaleAspectFit
        }
        
        NSLayoutConstraint.activate(logoConstraints)
        layoutIfNeeded()
    }
}
