//
//  IMAudioFlagView.swift

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

import UIKit
import Lottie

/// icon + 时长
class IMAudioFlagView: UIView{
    
    var stackH: UIStackView!
    
    var iconContainer: UIView!
    var iconStatic: UIImageView!
    var lottieView: LottieAnimationView!
    
    var secondsLabel: CLLabel!
    
    var topButton: UIButton!
    
    var seconds: Int?
    
    // MARK: - SpeechModel Properties
    private var path: String = ""
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .c.csfn
        cornerRadius = 8
        self.snp.makeConstraints { make in
            make.height.equalTo(28)
        }
        
        stackH = {
            let v = UIStackView()
            v.spacing = 8
            v.alignment = .center
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(12)
                make.trailing.equalToSuperview().offset(-12)
            }
            return v
        }()
        
        iconContainer = {
            let v = UIView()
            stackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 12, height: 12))
            }
            return v
        }()
        
        iconStatic = {
            let v = UIImageView()
            v.image = MWIconFont.image(fromIcon: .play, size: CGSize(width: 12, height: 12), color: .white)
            iconContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        lottieView = {
            let animation = LottieAnimation.named("voice_white")
            let voiceAnimation = LottieAnimationView(animation: animation)
            
            voiceAnimation.isUserInteractionEnabled = false
            voiceAnimation.loopMode = .loop
            voiceAnimation.animationSpeed = 1.4
            voiceAnimation.contentMode = .scaleAspectFit
            voiceAnimation.isHidden = true
            voiceAnimation.tintColor = .white
            iconContainer.addSubview(voiceAnimation)
            voiceAnimation.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.size.equalTo(CGSize(width: 12, height: 12))
            }
            voiceAnimation.isHidden = true
            return voiceAnimation
        }()
        
        secondsLabel = {
            let label = CLLabel()
            label.font = .t.tls
            label.isHidden = true
            stackH.addArrangedSubview(label)
            return label
        }()
        
        topButton = {
            let v = UIButton()
            v.touchAreaInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        secondsLabel.isHidden = false
        secondsLabel.text = "4''"
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - SpeechModel State Management
    func reloadState(with model: SpeechModel?) {
        guard let speechModel = model else {
            reset()
            return
        }
        self.path = speechModel.path
        speechModel.stateChangedBlock = { [weak self] updatedModel in
            guard let self = self, self.path == updatedModel.path else { return }
            self.reloadViews(model: updatedModel)
            self.checkState(model: updatedModel)
        }
        
        let duration = speechModel.audioDuration
        if duration > 0 {
            secondsLabel.isHidden = false
            secondsLabel.text = duration.imAIaudioDurationString
        }
        
        speechModel.progressChangedBlock = {[weak self] current, total in
            self?.secondsLabel.isHidden = false
            self?.secondsLabel.text = total.imAIaudioDurationString
        }
        
        reloadViews(model: speechModel)
    }
    
    // MARK: - Private Methods
    private func reloadViews(model: SpeechModel) {
        if model.loadState == .loading {
            startLoading()
        } else {
            reset()
        }
        if model.playState == .playing {
            startVoice()
        } else {
            reset()
        }
    }
    
    private func checkState(model: SpeechModel) {
        guard model.loadState == .complete else { return }
        
        switch model.playState {
        case .default:
            if model.canAutoPlay {
                SpeechManager.shared.startPlay(with: model)
            }
        case .complete, .failed:
            SpeechManager.shared.stopPlay(with: model)
        case .playing:
            break
        }
    }
    
    // MARK: - Original Methods (Modified)
    func reset(){
        lottieView.stop()
        lottieView.isHidden = true
        iconStatic.isHidden = false
    }
    
    func startLoading(){
        lottieView.animation = LottieAnimation.named("single_ring")
        lottieView.isHidden = false
        iconStatic.isHidden = true
        lottieView.play()
    }
    
    func startVoice(){
        lottieView.animation = LottieAnimation.named("voice_white")
        lottieView.isHidden = false
        iconStatic.isHidden = true
        lottieView.play()
    }
    
    // MARK: - Deinit
    deinit {
        //print("♻️ IMAudioFlagView dealloc")
    }
}
