//
//  ActionSheet.swift

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

import UIKit

// MARK: - Constants
private let kHeightTitle: CGFloat = 60
private let kHeightButton: CGFloat = 48
private let kButtonVPadding: CGFloat = 24
private let kHeightBottomLine: CGFloat = 0

// MARK: - EGActionSheetAction

class EGActionSheetAction {
    var title: String
    var autoDismiss: Bool
    var actionBlock: (() -> Void)?
    // Optional
    var iconLeading:UIImage?
    
    init(title: String, iconLeading: UIImage? = nil, autoDismiss: Bool, actionBlock: (() -> Void)?) {
        self.title = title
        self.iconLeading = iconLeading
        self.autoDismiss = autoDismiss
        self.actionBlock = actionBlock
    }
    
    static func action(title: String, block: (() -> Void)? = nil) -> EGActionSheetAction {
        return action(title: title, autoDismiss: true, block: block)
    }
    
    static func action(title: String, autoDismiss: Bool, block: (() -> Void)?) -> EGActionSheetAction {
        return EGActionSheetAction(title: title, autoDismiss: autoDismiss, actionBlock: block)
    }
}

// MARK: - EGActionSheet

class EGActionSheet: EGPopBaseView {
    // MARK: - Properties
    private var titleView: UIView!
    private var titleLabel: UILabel!
    private var closeButton: EPIconGhostButton!
    private var btsStackV: UIStackView!
    
    private var buttons: [UIButton] = []
    private var actions: [EGActionSheetAction] = []
    
    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    
    var cancelBlock: (() -> Void)?
    
    // MARK: - Initialization
    init() {
        super.init(direction: .bottom)
        dataInit()
        uiInit()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func dataInit() {
        contentView.backgroundColor = .c.csbn; //- Replace with EPSystemToken equivalent (EPS_Color_Surface_base_normal)
        animateDuration = 0.35
    }
    
    private func uiInit() {
        contentView.layer.cornerRadius = 24
        contentView.layer.masksToBounds = true
        contentView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        
        // Title View
        titleView = UIView()
        contentView.addSubview(titleView)
        titleView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            titleView.heightAnchor.constraint(equalToConstant: 48),
            titleView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            titleView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            titleView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12)
        ])
        
        // Close Button
        closeButton = EPIconGhostButton(radius: .none, iconSize: .small, iconCode: .delete)
        closeButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        titleView.addSubview(closeButton)
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            closeButton.trailingAnchor.constraint(equalTo: titleView.trailingAnchor, constant: -8),
            closeButton.centerYAnchor.constraint(equalTo: titleView.centerYAnchor),
            closeButton.widthAnchor.constraint(equalToConstant: 48),
            closeButton.heightAnchor.constraint(equalToConstant: 48)
        ])
        
        // Title Label
        titleLabel = UILabel()
        titleLabel.font = CLSystemToken.font(token: .tts) //  (EPS_Txt_Title_s)
        titleLabel.textColor = .c.ctpn // (EPS_Color_Txt_primary_normal)
        titleLabel.textAlignment = .center
        titleView.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(greaterThanOrEqualTo: titleView.leadingAnchor, constant: 24),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: closeButton.leadingAnchor, constant: -8),
            titleLabel.centerXAnchor.constraint(equalTo: titleView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: titleView.centerYAnchor)
        ])
        
        // Button Stack View
        btsStackV = UIStackView()
        btsStackV.spacing = 24
        btsStackV.axis = .vertical
        contentView.addSubview(btsStackV)
        btsStackV.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            btsStackV.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24),
            btsStackV.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24),
            btsStackV.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: 24),
            btsStackV.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -24 - UIWindow.safeAreaBottom)
        ])
        
        titleLabel.text = NSLocalizedString("More", comment: "")
    }
    
    // MARK: - Lifecycle
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        updateContentHeight()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // Additional layout logic if needed
    }
    
    // MARK: - Data
    private func updateContentHeight() {
        var height: CGFloat = 24 + UIWindow.safeAreaBottom + 24 + (48 + 12)
        if !buttons.isEmpty {
            height += CGFloat(buttons.count) * kHeightButton
            height += CGFloat(buttons.count - 1) * btsStackV.spacing
        }
        setContentLength(height)
    }
    
    // MARK: - Actions
    func addAction(_ action: EGActionSheetAction, propertySetup: ((UIButton) -> Void)? = nil) {
        let button = StyleButton(type: .custom)
        button.tertiary(size: .large)
        button.setTitle(action.title, for: .normal)
        button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
        button.tag = actions.count
        
        if let iconLeading = action.iconLeading{
            let iv = UIImageView()
            iv.image = iconLeading
            button.addSubview(iv)
            iv.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(24)
            }
        }
        
        btsStackV.addArrangedSubview(button)
        
        if let propertySetup = propertySetup {
            propertySetup(button)
        }
        
        actions.append(action)
        buttons.append(button)
        
        updateContentHeight()
    }
    
    // MARK: - Events
    override func bgButtonPressed(_ button: UIButton) {
        cancelBlock?()
        super.bgButtonPressed(button)
    }
    
    @objc private func cancelButtonPressed(_ button: UIButton) {
        cancelBlock?()
        dismiss()
    }
    
    @objc private func buttonPressed(_ button: UIButton) {
        let action = actions[button.tag]
        if action.autoDismiss {
            dismiss()
        }
        action.actionBlock?()
    }
}
