//
//  TSChatInputFullScreenVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/14.
//

import UIKit

class TSChatInputFullScreenVC: TSBaseVC, UITextViewDelegate {
    
    var sendComplete:(([Any])->Void)?
    var closeComplete:((String)->Void)?
    var text:String?
    //AI是否正在回答问题
    var isAIAnswering:Bool = false{
        didSet{
            sendEnabled(enabled: !isAIAnswering)
        }
    }
    
    lazy var InputBarView:UIView = {
        let InputBarView = UIView()
        InputBarView.backgroundColor = "#222222".uiColor
        InputBarView.cornerRadius = 28.0
        return InputBarView
    }()
    
    lazy var sendBtn: UIButton = {
        let sendBtn = UIButton.createButton(image: UIImage(named: "chat_send")) { [weak self]  in
            guard let self = self else { return }
            sendMsg()
        }
        return sendBtn
    }()
    
    lazy var minificationBtn: UIButton = {
        let minificationBtn = UIButton.createButton(image: UIImage(named: "chat_send_minify")) { [weak self]  in
            guard let self = self else { return }
            closeComplete?(textView.text)
            self.dismiss(animated: true)
        }
        return minificationBtn
    }()
    
    private let minHeight: CGFloat = 24
    private let maxHeight: CGFloat = 154
    lazy var textView: TSCustomTextView = {
        let textView = TSCustomTextView()
        textView.backgroundColor = .clear
        textView.textColor = .white
        textView.delegate = self
        textView.font = .font(size: 16)
        textView.clipsToBounds = true
        textView.isScrollEnabled = false
        textView.tintColor = .themeColor
        textView.returnKeyType = .send
        textView.placeholder = "Type all necessary details".localized
        textView.placeholderColor = .white.withAlphaComponent(0.4)
        textView.placeholderLabel.font = .font(size: 16.0)
        textView.textInsets = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)
        return textView
    }()
  
    override func createView() {
        setNavBarViewHidden(true)
        edgesForExtendedLayout = []
        
        contentView.addSubview(InputBarView)
        InputBarView.addSubview(textView)
        InputBarView.addSubview(minificationBtn)
        InputBarView.addSubview(sendBtn)
        
        InputBarView.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.top.equalTo(12+k_Height_NavBar)
            make.bottom.equalTo(-12-k_Height_safeAreaInsetsBottom())
        }
        
        textView.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-60)
            make.top.equalTo(16)
            make.bottom.equalTo(-16)
            make.height.equalTo(minHeight)
        }
        
        sendBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.bottom.equalTo(-16)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        
        minificationBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.top.equalTo(16)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
    }
    

    override func dealThings() {
        textView.text = text
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickView))
        tapGesture.cancelsTouchesInView = false
        InputBarView.addGestureRecognizer(tapGesture)
        
        // 监听文本变化事件
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: UITextView.textDidChangeNotification, object: textView)

        // 监听键盘事件
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleAIAnsweringNotification(_:)), name: .kAIAnsweringNotification, object: nil)
    }

    @objc func clickView(){
        view.endEditing(true)
    }
    
    @objc private func textDidChange() {
        sendEnabled(enabled: textView.text.count > 0)
    }
    
    
    func sendMsg(){

        if sendBtn.isEnabled == false {
            return
        }
        
//        if textView.text.replacingOccurrences(of: " ", with: "").count <= 0 {
//            return
//        }
        
        if let string = textView.text {
            sendComplete?([string])
            textView.resignFirstResponder()
            dismiss(animated: true)
        }
    }
    
    func sendEnabled(enabled:Bool){
        if enabled == true,
           isAIAnswering == false,
            textView.text.replacingOccurrences(of: " ", with: "").count > 0 {
            sendBtn.isEnabled = true
        }else{
            sendBtn.isEnabled = false
        }
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {

        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
              let animationDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else {
            return
        }

        let keyboardHeight = keyboardFrame.height
        let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)

        UIView.animate(withDuration: animationDuration) {
            self.textView.contentInset = contentInset
            self.textView.scrollIndicatorInsets = contentInset
        }
        
        UIView.animate(withDuration: animationDuration+0.8) {
            self.sendBtn.snp.updateConstraints { make in
                make.bottom.equalTo(-keyboardHeight + k_Height_safeAreaInsetsBottom())
            }
        }
    }

    @objc func keyboardWillHide(_ notification: Notification) {
        guard let animationDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else {
            return
        }

        let contentInset = UIEdgeInsets.zero
        UIView.animate(withDuration: animationDuration) {
            self.textView.contentInset = contentInset
            self.textView.scrollIndicatorInsets = contentInset
            
            self.sendBtn.snp.updateConstraints { make in
                make.bottom.equalTo(-16)
            }
        }
    }
    
    
    @objc func handleAIAnsweringNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let boolValue = userInfo[kIsAIAnswering] as? Bool {
            isAIAnswering = boolValue
        }
    }
    
    deinit {
        // 移除通知监听
        NotificationCenter.default.removeObserver(self)
    }
}

extension TSChatInputFullScreenVC {
    
    // 实现 UITextViewDelegate 协议方法，控制 return 键行为
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            // 当输入为换行符（即按下 return 键）时，执行相应操作
            sendMsg()
            return false
        }
        return true
    }
}
