//
//  LNToastView.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/15.
//

import Foundation
import UIKit
import SnapKit


var allToast = NSHashTable<UIView>(options: .weakMemory)

func showToast(_ toast: String?, icon: UIImage? = nil) {
    guard let toast, !toast.isEmpty else { return }
    
    runOnMain {
        let view = LNToastView()
        view.show(toast, icon: icon)
    }
}

func cleanToasts() {
    allToast.allObjects.forEach { $0.removeFromSuperview() }
}

class LNToastView: UIView {
    private let iconView = UIImageView()
    private let textLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func show(_ toast: String, icon: UIImage? = nil) {
        textLabel.text = toast
        iconView.image = icon
        iconView.isHidden = icon == nil
        
        guard let window = UIView.appKeyWindow else { return }
        window.addSubview(self)
        self.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            if LNKeyboardManager.shared.isEditing {
                make.centerY.equalToSuperview().multipliedBy(0.8)
            } else {
                make.centerY.equalToSuperview().multipliedBy(1.1)
            }
            make.leading.greaterThanOrEqualToSuperview().offset(56)
        }
        
        allToast.add(self)
        
        LNDelayTask.perform(delay: 2.5) { [weak self] in
            guard let self else { return }
            UIView.animate(withDuration: 0.3) { [weak self] in
                guard let self else { return }
                alpha = 0
            } completion: { [weak self] _ in
                guard let self else { return }
                removeFromSuperview()
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNToastView {
    private func setupViews() {
        layer.cornerRadius = 18
        backgroundColor = .black.withAlphaComponent(0.8)
        
        let stackView = UIStackView()
        stackView.spacing = 4
        stackView.axis = .vertical
        stackView.alignment = .center
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.verticalEdges.equalToSuperview().inset(12)
        }
    
        stackView.addArrangedSubview(iconView)
        iconView.snp.makeConstraints { make in
            make.width.height.equalTo(32)
        }
        
        textLabel.font = .body_m
        textLabel.textColor = .text_1
        textLabel.numberOfLines = 0
        stackView.addArrangedSubview(textLabel)
    }
}
