//
//  IndicatorView.swift

//
//  Created by Leon on 2025/8/1.
//

import UIKit

class IndicatorView: UIView {
    // MARK: - Properties

    private var icon: UIImageView!
    private var circleColor: UIColor
    private var _size: CGSize = CGSize(width: 16, height: 16)

    override var size: CGSize {
        get { _size }
        set {
            _size = newValue
            icon.snp.updateConstraints { make in
                make.size.equalTo(newValue)
            }
        }
    }

    var isAnimating: Bool {
        return icon.layer.animation(forKey: "rotationAnimation") != nil
    }

    // MARK: - Initialization

    init(color: UIColor) {
        circleColor = color
        super.init(frame: .zero)
        initialViews()
    }

    override init(frame: CGRect) {
        circleColor = .black // Default color when not specified
        super.init(frame: frame)
        initialViews()
    }

    required init?(coder: NSCoder) {
        circleColor = .black
        super.init(coder: coder)
        initialViews()
    }

    // MARK: - Setup

    private func initialViews() {
        backgroundColor = .clear

        icon = UIImageView()
        icon.contentMode = .scaleAspectFit

        let color = circleColor // Fallback to primary text color if needed
        icon.image = generateIconImage(size: _size, color: color)

        addSubview(icon)
        icon.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(_size)
        }
    }
    
    // MARK: - Preset Style
    
    func setupGeneratingAIPicStyle(){
        size = CGSize(width: 96, height: 96)
        icon.image = UIImage(named: "generating_indicator")
    }

    // MARK: - Animation

    func startIndicator() {
        isHidden = false
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0)
        rotationAnimation.duration = 1.0
        rotationAnimation.isRemovedOnCompletion = false
        rotationAnimation.isCumulative = true
        rotationAnimation.repeatCount = .infinity
        icon.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }

    func stopIndicator() {
        isHidden = true
        icon.layer.removeAllAnimations()
    }

    func startAnimating() {
        startIndicator()
    }

    func stopAnimating() {
        stopIndicator()
    }

    // MARK: - Helper Methods

    private func generateIconImage(icon: IconCode = .loading, size: CGSize, color: UIColor) -> UIImage? {
        return MWIconFont.image(fromIcon: icon, size: size, color: color)
    }

    // MARK: - Deinit

    deinit {
        stopIndicator()
        print("♻️ dealloc EPIndicatorView")
    }
}
