//
//  IMVoiceHoldView.swift

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

import UIKit
import Lottie
class IMVoiceHoldView: UIView {
//    var gradientBg: GradientView!
    var overlayBg: UIImageView!

    var voiceWaveContainer: GradientView!
    var wave : LottieAnimationView!
    
    var swipeStackView: UIStackView!
    var swipeLab: UILabel!
    var swipeImgView: UIImageView!

    var tipLabel: UILabel!

    var voiceIconDecorationView: UIImageView!
    var voiceIcon: UIImageView!

    var recordTool: AudioRecordTool!
    // State
    var audioDuration: Int = 0
    var counting: Int = 0
    private var isRecording: Bool = false
    public var audioPathUrl: URL?

    var recordFinishedAction: ((_ url: URL?) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        isUserInteractionEnabled = false

        snp.makeConstraints { make in
            make.height.equalTo(300)
        }
        
        overlayBg = {
            let v = UIImageView()
            v.contentMode = .scaleToFill
            v.image = UIImage(named: "voice_hold_overlay_bot")
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        voiceIconDecorationView = {
            let v = UIImageView()
            v.image = UIImage(named: "role_chat_voice_normal")
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.bottom.equalToSuperview()
                make.height.equalTo(v.snp.width).multipliedBy(171/375.0)
            }
            return v
        }()


        voiceWaveContainer = {
//            let gradient = CLSystemToken.gradient(token: .cpgn)
//            let v = GradientView(colors: gradient.colors(), gradientType: .leftToRight)
            let v = GradientView(colors: [UIColor.clear], gradientType: .leftToRight)

            v.cornerRadius = 24
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(voiceIconDecorationView.snp.top).offset(10)
                make.centerX.equalToSuperview()
                make.width.equalTo(120)
                make.height.equalTo(48)
            }

            return v
        }()
        
        wave = {
            let animation = LottieAnimation.named("voice_im_recording")
            let voiceAnimation = LottieAnimationView(animation: animation)
            // voiceAnimation = LottieAnimationView.animationNamed("voice_white.json")
            voiceAnimation.isUserInteractionEnabled = false
            voiceAnimation.loopMode = .loop
            voiceAnimation.animationSpeed = 1.4
            voiceAnimation.contentMode = .scaleAspectFit
            voiceAnimation.tintColor = .white
            voiceAnimation.play()
            voiceWaveContainer.addSubview(voiceAnimation)
            voiceAnimation.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalToSuperview().offset(12)
                make.bottom.equalToSuperview().offset(-12)
                make.width.equalTo(voiceAnimation.snp.height).multipliedBy(470/80.0)
            }
            voiceAnimation.isHidden = false
            return voiceAnimation
        }()
        
        swipeLab = {
            let lab = UILabel()
            lab.text = "Swipe Up to Cancel"
            lab.textColor = UIColor.white
            lab.font = UIFont.systemFont(ofSize: 12)
            return lab
        }()
        
        swipeImgView = {
            let imgView = UIImageView(image: UIImage(named: "role_chat_up_cancel"))
            return imgView
        }()
        
        swipeStackView = {
            let stackView = UIStackView(arrangedSubviews: [swipeImgView, swipeLab])
            stackView.spacing = 5.0
            stackView.distribution = .fill
            stackView.alignment = .fill
            insertSubview(stackView, belowSubview: overlayBg)
            stackView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(voiceIconDecorationView.snp.top).offset(-15)
            }
            return stackView
        }()

        tipLabel = {
            let v = UILabel()
            v.font = .t.tlm
            v.textColor = .desc
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(voiceWaveContainer.snp.bottom).offset(0)
            }
            return v
        }()

        tipLabel.text = "Release to send"
    }

    private func setupData() {
        recordTool = AudioRecordTool()
    }

    private func setupEvent() {
        recordTool.timerChangedBlock = { [weak self] counting in
            self?.counting = counting
            //let seconds = CGFloat(counting) / 10.0
            // dlog("麦克风\(seconds)s")

            if counting >= 60 * 10 - 1 {
                self?.stopRecord()
                
                return
            }
        }
    }

    // MARK: - Public

    func record(on: Bool) {
        
        CLTool.feedbackGenerator()
        isRecording = on

        if on {
            wave.play()
            recordTool.startRecord { [weak self] audioURL in
                self?.audioPathUrl = audioURL
                dlog("☁️🎤audioURL: \(String(describing: audioURL))")
                
                if let count = self?.counting, count < 10{
                    Hud.toast(str: "语音时间太短")
                    return
                }
                self?.recordFinishedAction?(audioURL)
            }
        } else {
            wave.stop()
            stopRecord()
        }
    }

    // MARK: - Functions

    func stopRecord() {
        recordTool.stopRecord()
//        if counting < 10{
//            Hud.toast(str: "语音时间太短")
//            return
//        }
        
    }

    // MARK: - Other
}
