//
//  HomeQuickActionsView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 首页快捷操作按钮区。
final class HomeQuickActionsView: UIView {

    var onCollectPayment: (() -> Void)?
    var onSubmitTask: (() -> Void)?
    var onToggleOnline: (() -> Void)?

    private let stackView = UIStackView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = AppSpacing.sm
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo(72)
        }
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func apply(isOnline: Bool) {
        stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        stackView.addArrangedSubview(makeActionButton(title: "立即收款", icon: "yensign.circle", action: #selector(collectPaymentTapped)))
        stackView.addArrangedSubview(makeActionButton(title: "提交任务", icon: "doc.text", action: #selector(submitTaskTapped)))
        stackView.addArrangedSubview(makeActionButton(
            title: isOnline ? "在线" : "离线",
            icon: isOnline ? "dot.radiowaves.left.and.right" : "moon",
            action: #selector(toggleOnlineTapped)
        ))
    }

    private func makeActionButton(title: String, icon: String, action: Selector) -> UIView {
        let container = UIView()
        container.backgroundColor = AppColor.cardBackground
        container.layer.cornerRadius = AppRadius.md

        let button = UIButton(type: .system)
        button.addTarget(self, action: action, for: .touchUpInside)
        container.addSubview(button)
        button.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let imageView = UIImageView(image: UIImage(systemName: icon))
        imageView.tintColor = AppColor.primary
        imageView.contentMode = .scaleAspectFit

        let label = UILabel()
        label.text = title
        label.font = .app(.bodyMedium)
        label.textColor = AppColor.textPrimary
        label.textAlignment = .center

        let column = UIStackView(arrangedSubviews: [imageView, label])
        column.axis = .vertical
        column.alignment = .center
        column.spacing = 6
        column.isUserInteractionEnabled = false
        container.addSubview(column)
        column.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        imageView.snp.makeConstraints { make in
            make.width.height.equalTo(22)
        }
        return container
    }

    @objc private func collectPaymentTapped() { onCollectPayment?() }
    @objc private func submitTaskTapped() { onSubmitTask?() }
    @objc private func toggleOnlineTapped() { onToggleOnline?() }
}
