//
//  ToastView.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/23.
//

import Foundation
import UIKit

public class HUDConfig: THUDProtocol {
    var blur: Bool = false
    var backgroundColor: UIColor?
    
    var minWidth: CGFloat? = 156
    var loadingSize: CGSize = CGSize(width: 24, height: 24)
    
    // 状态
    var stateMessage: String?
    var stateImage: UIImage?
    // 描述
    var descMessage: String?
    // 按钮
    var actionTitle: String?
    // 按钮事件，true：取消，false：按钮点击
    var actionHandler: ((Bool) -> Void)?
    var closeable: Bool = false
    
    public var hudView: THUDViewProtocol {
        let v = ToastView(model: self)
        if blur {
            let blurView = ToastBlurView()
            blurView.identifier = self.stateMessage
            blurView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
            blurView.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            blurView.frame = UIScreen.main.bounds
            return blurView
        }
        return v
    }
    
    public var hudDuration: TimeInterval? {
        return nil
    }
}

class ToastBlurView: UIView, THUDViewProtocol {
    var identifier: String?
    
    var hudIdentifier: String? {
        return identifier
    }
}

class ToastView: UIView, THUDViewProtocol {
    lazy var loadingIV = UIImageView(image: UIImage(named: "ic-rotate-loading"))
    lazy var stateImageView = UIImageView()
    lazy var stateLabel = UILabel()
    lazy var messageLabel = UILabel()
    lazy var actionButton: UIButton = {
        let bt = UIButton()
        bt.setTitle("", for: .normal)
        bt.setTitleColor(.white, for: .normal)
        bt.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        bt.backgroundColor = UIColor.white.withAlphaComponent(0.1)
        bt.customCornerRadius = 18
        bt.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
        return bt
    }()
    lazy var closeButton: UIButton = {
        let bt = UIButton()
        bt.setImage(UIImage(named: "ic-close"), for: .normal)
        bt.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
        bt.isHidden = true
        return bt
    }()
    
    lazy var model = HUDConfig()
    required init(model: HUDConfig) {
        super.init(frame: .zero)
        self.model = model
        
        customCornerRadius = 16
        backgroundColor = model.backgroundColor ?? .hexColor("#262626")
        
        let stackView = UIStackView(arrangedSubviews:
                                        [loadingIV,
                                         stateImageView,
                                         stateLabel,
                                         messageLabel,
                                         actionButton])
        stackView.axis = .vertical
        stackView.spacing = 10
        stackView.distribution = .fill
        stackView.alignment = .center
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.bottom.equalTo(-16)
            if let width = model.minWidth {
                make.width.greaterThanOrEqualTo(width)
            }
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        loadingIV.contentMode = .scaleAspectFit
        loadingIV.snp.makeConstraints { make in
            make.size.equalTo(model.loadingSize)
        }
        
        loadingIV.isHidden = model.stateImage != nil
        stateImageView.isHidden = model.stateImage == nil
        stateImageView.contentMode = .scaleAspectFit
        stateImageView.snp.makeConstraints { make in
            make.width.height.equalTo(30)
        }
        
        stateLabel.isHidden = model.stateMessage?.isEmpty ?? true
        stateLabel.snp.makeConstraints { make in
            make.height.equalTo(18)
        }
        
        messageLabel.isHidden = model.descMessage?.isEmpty ?? true
        messageLabel.snp.makeConstraints { make in
            make.height.equalTo(18)
        }
        
        actionButton.isHidden = model.actionTitle == nil
        actionButton.setTitle(model.actionTitle, for: .normal)
        actionButton.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        
        closeButton.isHidden = !model.closeable
        addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.top.equalTo(4)
            make.right.equalTo(-4)
            make.width.height.equalTo(24)
        }
        
        stateImageView.image = model.stateImage
        
        stateLabel.font = .systemFont(ofSize: 12)
        stateLabel.textColor = .white
        stateLabel.text = model.stateMessage
        
        messageLabel.font = .systemFont(ofSize: 12)
        messageLabel.textColor = .white
        messageLabel.text = model.descMessage
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
//        setGradient(colors: AppTheme.gradientAlphaColors, index: 0)
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        if superview != nil {
            startLoadingAnimation()
        } else {
            loadingIV.layer.removeAllAnimations()
        }
    }
    
    @objc private func buttonClick(_ sender: UIButton) {
        switch sender {
        case actionButton:
            model.actionHandler?(false)
        case closeButton:
            model.actionHandler?(true)
        default:
            break
        }
    }
    
    private func startLoadingAnimation() {
        // 1.创建动画
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        // 2.设置动画属性
        animation.fromValue = 0 // 开始角度
        animation.toValue = Double.pi * 2 // 结束角度
        animation.repeatCount = .greatestFiniteMagnitude // 重复次数
        animation.duration = 1
        // 动画完成后自动重新开始,默认为NO
        animation.autoreverses = false
        // 默认是true，切换到其他控制器再回来，动画效果会消失，需要设置成false，动画就不会停了
        animation.isRemovedOnCompletion = false
        // 给需要旋转的view增加动画
        loadingIV.layer.add(animation, forKey: nil)
    }
    
    var hudIdentifier: String? {
        return stateLabel.text
    }
}
