//
//  SpeakDialogueInputTextView.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/7.
//

import UIKit


protocol SpeakDialogueInputDelegate:NSObject {
    
    /// 点击提示
    func SpeakTipComplate() -> Void
    /// 发送消息
    func speakSendMessage(message:String) -> Void
    /// 开始录音
    func startRecord() -> Void
    /// 取消录音
    func cancelRecord() -> Void
    
}


class SpeakDialogueInputTextView: UIView {

    enum InputTextState {
        case defult
        case record
        case recording
        case Inputing
    }
    
    // MARK: - ib
    @IBOutlet weak var SpeakDialogInputType: UIButton!
    @IBOutlet weak var SpeakDialogInputText: SpeakDialogueBaseTextView!
    @IBOutlet weak var SpeakDialogTip: UIButton!
    @IBOutlet weak var SpeakSendTel: UIButton!
    
    @IBOutlet weak var SpeakRecordView: UIView!
    @IBOutlet weak var SpeakRecordTip: UILabel!
    @IBOutlet weak var SpeakRecordAnimat: UIView!
    @IBOutlet weak var SpeakRecordTimes: UILabel!
    @IBOutlet weak var SpeakRecordSStop: UILabel!
    
    @IBOutlet weak var SpeakRecordAudio: UIImageView!
    
    weak var delegate:(SpeakDialogueInputDelegate)?
    private var offsets:Int = 30
    
    
    static func xib() -> SpeakDialogueInputTextView {
        let nib = UINib(nibName: "SpeakDialogueInputTextView", bundle: nil).instantiate(withOwner: nil).first as! SpeakDialogueInputTextView
        return nib
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        SpeakDialogInputText.delegate = self
        SpeakRecordAudio.loadGif(name: "语音输入_00000_iSpt",oftype: "png",repeatCount: 0)
        SpeakRecordView.gesture(gesture: .tap) {[weak self] db in
            if SpeakAudioRecorder.shared.hasPermission && SpeakAudioRecorder.shared.isRecording == false /* && SpeakAudioToTextConverter.share.checkPermissions()*/ {
                self?.offsets = 30
                self?.SpeakRecordView.isUserInteractionEnabled = false
                self?.SpeakRecordTimes.text = "00:30"
                self?.delegate?.startRecord()
                self?.state = .recording
            }else{
                let alert = UIAlertController(title: nil, message: "Microphone permission not enabled", preferredStyle: .alert)
                SpWindow.rootViewController?.present(alert, animated: true)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    alert.dismiss(animated: true)
                }
            }
        }
    }
    
    func update(){
        offsets -= 1
        SpeakRecordTimes.text = String(format: "00:%02d", offsets)
        if offsets <= 10 && state == .recording {
            SpeakRecordAnimat.isHidden = true
            SpeakRecordTimes.isHidden = true
            SpeakRecordSStop.isHidden = false
            SpeakRecordSStop.text = "Stop recording in \(offsets)s"
        }else if offsets <= 0 && state == .recording {
            state = .record
            delegate?.speakSendMessage(message: "")
            self.SpeakRecordView.isUserInteractionEnabled = true
        }
    }

    var state:InputTextState = .defult {
        didSet {
            switch state {
            case .defult:
                SpeakDialogInputType.isHidden = false
                if SpeakElePublicManager.share.PublicData.Smarttips == false {
                    SpeakDialogTip.isHidden = false
                }else{
                    SpeakDialogTip.isHidden = true
                }
                SpeakSendTel.setImage(UIImage(named: "icon_dialogue_tonghua_on"), for: .normal)
                SpeakSendTel.isHidden = false
                SpeakDialogInputType.setImage(UIImage(named: "icon_dialogue_yuying"), for: .normal)
                SpeakDialogInputType.setImage(nil, for: .selected)
                
                SpeakDialogInputText.isHidden = false
                SpeakRecordView.isHidden = true
                break
            case .record:
                SpeakDialogInputType.setImage(UIImage(named: "icon_dialogue_keyboard"), for: .normal)
                SpeakSendTel.setImage(UIImage(named: "icon_dialogue_tonghua_on"), for: .normal)
                SpeakSendTel.isHidden = false
                SpeakDialogTip.isHidden = true
                
                SpeakDialogInputText.isHidden = true
                SpeakRecordView.isHidden = false
                
                SpeakRecordTip.isHidden = false
                SpeakRecordAnimat.isHidden = true
                SpeakRecordTimes.isHidden = true
                SpeakRecordSStop.isHidden = true
                break
            case .Inputing:
                SpeakDialogInputType.isHidden = true
//                if SpeakElePublicManager.share.PublicData.Smarttips == false {
//                    SpeakDialogTip.isHidden = false
//                }else{
//                    SpeakDialogTip.isHidden = true
//                }
                SpeakDialogTip.isHidden = true
                SpeakSendTel.isHidden = false
                SpeakSendTel.setImage(UIImage(named: "sp-guide-Send"), for: .normal)
                
                break
            case .recording:
                SpeakDialogInputType.isSelected = true
                SpeakSendTel.setImage(UIImage(named: "sp-guide-Send"), for: .normal)
                SpeakDialogInputType.setImage(UIImage(named: "icon_dialogue_back"), for: .normal)
                
                SpeakRecordTip.isHidden = true
                SpeakRecordAnimat.isHidden = false
                SpeakRecordTimes.isHidden = false
                break
            }
        }
    }
    
    
    @IBAction func SpeakDialogToggleTaps(_ sender: UIButton) {
        AudioPlayerManager.shared.task = []
        if state == .defult {
            state = .record
        }else if (state == .record){
            state = .defult
            SpeakAudioRecorder.shared.stopRecording()
        }else if state == .recording {
            state = .record
            self.SpeakRecordView.isUserInteractionEnabled = true
            delegate?.cancelRecord()
        }
    }
    
    @IBAction func SpeakDialogTipTaps(_ sender: Any) {
        delegate?.SpeakTipComplate()
    }
    
    @IBAction func SpeakDialogSendCallTaps(_ sender: UIButton) {
        AudioPlayerManager.shared.task = []
        if state == .defult || state == .record{
            if let call = callblack {
                call("")
            }
        }else if state == .Inputing {
            if !(SpeakDialogInputText.text ?? "").isEmpty {
                delegate?.speakSendMessage(message: SpeakDialogInputText.text ?? "")
                SpeakDialogInputText.text = ""
                self.endEditing(true)
            }
        }else if state == .recording {
            state = .record
            delegate?.speakSendMessage(message: "")
            self.SpeakRecordView.isUserInteractionEnabled = true
        }
    }
}

extension SpeakDialogueInputTextView : UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        state = .Inputing
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        state = .defult
    }
}
