//
//  CLSelectView.swift

//
//  Created by Leon on 2025/7/18.
//

import UIKit
import SnapKit

class CLSelectView: UIView {
    // MARK: - Properties
    var titleLabel: UILabel
    var arrowImageView: UIImageView
    var backButton: UIButton
    
    var placeholder: String? {
        didSet {
            setupTheme()
            if contentStr == nil || contentStr!.isEmpty {
                contentLabel.text = placeholder
                setupTheme()
            }
        }
    }
    
    var placeholderColor: UIColor? {
        didSet {
            setupTheme()
        }
    }
    
    var forceSupportLabelColor: UIColor? {
        didSet {
            setupTheme()
        }
    }
    
    var contentStr: String? {
        didSet {
            setupTheme()
            if let contentStr = contentStr, !contentStr.isEmpty {
                contentLabel.text = contentStr
                setupTheme()
                if enableClearMode {
                    closeButton.isHidden = false
                    arrowImageView.isHidden = true
                }
            } else {
                let place = self.placeholder
                placeholder = place
                if enableClearMode {
                    closeButton.isHidden = true
                    arrowImageView.isHidden = false
                }
            }
        }
    }
    
    var enableClearMode: Bool = false
    
    var isEnabled: Bool = true {
        didSet {
            isUserInteractionEnabled = isEnabled
            arrowImageView.isHidden = false
            if isEnabled {
                titleLabel.textColor = .c.ctpn
                backButton.backgroundColor = .c.csen
                contentLabel.textColor = .c.ctpn
                arrowImageView.image = MWIconFont.image(fromIcon: .arrowDownFill, size: CGSize(width: 16, height: 16), color: UIColor.c.ctsn, edgeInsets: .zero)
            } else {
                titleLabel.textColor = .c.ctd
                backButton.backgroundColor = .c.csed
                contentLabel.textColor = .c.ctd
                arrowImageView.isHidden = true
                //arrowImageView.image = MWIconFont.image(fromIcon: .arrowDownFill, size: CGSize(width: 16, height: 16), color: .c.ctsd, edgeInsets: .zero)
            }
            setupTheme()
        }
    }
    
    var selectBlock: (() -> Void)?
    var clearBlock: (() -> Void)?
    
    private var stackV: UIStackView
    private var queryButton: EPIconTertiaryButton?
    private var contentStackH: UIStackView
    private var contentLabel: UILabel
    private var supportLabel: UILabel
    private var closeButton: EPIconGhostSecondaryButton!
    private var tapQueryButton: (() -> Void)?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        titleLabel = UILabel()
        arrowImageView = UIImageView()
        backButton = UIButton(type: .custom)
        stackV = UIStackView()
        contentStackH = UIStackView()
        contentLabel = UILabel()
        supportLabel = UILabel()
        
        super.init(frame: frame)
        initialViews()
        isEnabled = true
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        initialViews()
        isEnabled = true
        setupTheme()
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func initialViews() {
        let heightOfBackButton: CGFloat = 48
        let titleBetweenBackButtonPadding = 8//EPGlobalToken.spacing(.space12)
        
        // Configure stack view
        stackV.axis = .vertical
        stackV.spacing = 4
        addSubview(stackV)
        stackV.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalTo(self)
        }
        
        // Configure back button
        stackV.addArrangedSubview(backButton)
        backButton.layer.cornerRadius = 8
        backButton.backgroundColor = .c.csen
        backButton.snp.makeConstraints { make in
            make.height.equalTo(heightOfBackButton)
        }
        backButton.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside)
        
        // Configure content stack
        contentStackH.isUserInteractionEnabled = false
        contentStackH.spacing = 8
        contentStackH.alignment = .center
        addSubview(contentStackH)
        contentStackH.snp.makeConstraints { make in
            make.left.equalTo(backButton).offset(16)
            make.right.lessThanOrEqualTo(self).offset(-24)
            make.centerY.equalTo(backButton)
        }
        
        // Configure content label
        contentLabel.font = CLSystemToken.font(token: .tbl)//EPSystemToken.typography(.txtBodyL).font
        contentStackH.addArrangedSubview(contentLabel)
        contentLabel.setContentCompressionResistancePriority(.init(749), for: .horizontal)
        
        // Configure title label
        titleLabel.font = CLSystemToken.font(token: .tlm)
        titleLabel.textColor = .c.ctpn
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(self)
            make.bottom.equalTo(backButton.snp.top).offset(-titleBetweenBackButtonPadding)
            make.top.equalTo(self).offset(0)
        }
        
        // Configure arrow image view
        arrowImageView.isHidden = false
        arrowImageView.image = MWIconFont.image(fromIcon: .arrowDownFill, size: CGSize(width: 16, height: 16), color: .c.ctsn, edgeInsets: .zero)
        addSubview(arrowImageView)
        arrowImageView.snp.makeConstraints { make in
            make.centerY.equalTo(backButton)
            make.right.equalTo(self).offset(-16)
            make.size.equalTo(CGSize(width: 16, height: 16))
        }
        
        // Configure support label
        supportLabel.font = CLSystemToken.font(token: .tbs)
        supportLabel.numberOfLines = 0
        supportLabel.textColor = .c.ctsn
        
        stackV.addArrangedSubview(supportLabel)
        
        // Default placeholder color
        placeholderColor = .c.cttn//EPSystemToken.color(.txtTertiaryNormal)
        
        setupTheme()
    }
    
    private func setupTheme() {
        if isEnabled{
            contentLabel.textColor = (contentStr?.isEmpty ?? true) ? placeholderColor : .c.ctpn
            supportLabel.textColor = forceSupportLabelColor ?? .c.civn
            backButton.layer.borderColor = UIColor.c.civn.cgColor
        }else{
            contentLabel.textColor = .c.ctpd
            supportLabel.textColor = .c.ctsd
        }
        
    }
    
    // MARK: - Actions
    @objc private func backButtonAction() {
        selectBlock?()
    }
    
    @objc private func tapCloseButton() {
        clearBlock?()
    }
    
    @objc private func tapQueryBtn() {
        tapQueryButton?()
    }
    
    // MARK: - Public Methods
    func setupSelect(canSelect: Bool, selectBlock: @escaping (String?) -> Void) {
        self.isEnabled = canSelect
        // Note: Original code doesn't use the selectBlock parameter; assuming it's a mistake
        // If needed, store selectBlock for use in backButtonAction
    }
    
    func showErrorMsg(_ string: String) {
        supportLabel.isHidden = false
        backButton.layer.borderWidth = CLSystemToken.border(token: .bs)
        //EPSystemToken.border(.borderS)
        supportLabel.text = string
    }
    
    func hideErrorInfo() {
        supportLabel.isHidden = true
        backButton.layer.borderWidth = 0
    }
    
    func showForceNormalSupportMsg(_ string: String) {
        guard !string.isEmpty else { return }
        forceSupportLabelColor = .c.ctsn
        supportLabel.isHidden = false
        supportLabel.text = string
        supportLabel.textColor = .c.ctsn
    }
    
    func titleAppendQuestionIcon(_ block: @escaping () -> Void) {
        if queryButton == nil {
            tapQueryButton = block
            queryButton = EPIconTertiaryButton(radius: .round, iconSize: .xxs, iconCode: .question)
            queryButton?.touchAreaInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            queryButton?.addTarget(self, action: #selector(tapQueryBtn), for: .touchUpInside)
            addSubview(queryButton!)
            queryButton?.snp.makeConstraints { make in
                make.leading.equalTo(titleLabel.snp.trailing).offset(8)
                make.centerY.equalTo(titleLabel)
                make.trailing.lessThanOrEqualTo(self).offset(-8)
            }
        }
        queryButton?.isHidden = false
    }
}
