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

import UIKit

class TSChatInputBarVC: TSBaseVC, UITextViewDelegate {
    
    var sendComplete:(([Any])->Void)?
    //AI是否正在回答问题
    var isAIAnswering:Bool = false{
        didSet{
            sendEnabled(enabled: !isAIAnswering)
//            chatInputFullScreenVC?.isAIAnswering = 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()
        }
        sendBtn.isEnabled = false
        return sendBtn
    }()
    
    lazy var magnifyBtn: UIButton = {
        let magnifyBtn = UIButton.createButton(image: UIImage(named: "chat_send_magnify")) { [weak self]  in
            guard let self = self else { return }
            let vc = TSChatInputFullScreenVC()
            
//            chatInputFullScreenVC = vc
            
            vc.text = textView.text
            vc.sendComplete = { [weak self] date in
                guard let self = self else { return }
//                chatInputFullScreenVC = nil
                if let text = date.first as? String {
                    textView.text = text
                    textView.resignFirstResponder()
                    textDidChange()
                    scrollTextViewToBottom()
                    sendComplete?(date)
                }
            }
            
            vc.closeComplete = { [weak self] text in
                guard let self = self else { return }
//                chatInputFullScreenVC = nil
                textView.text = text
                textView.resignFirstResponder()
                textDidChange()
                scrollTextViewToBottom()
            }
            
            kPresentModalVC(target: self, modelVC: vc)
            
        }
        magnifyBtn.isHidden = true
        return magnifyBtn
    }()
    
    
//    var chatInputFullScreenVC: TSChatInputFullScreenVC?
    
    private let minHeight: CGFloat = 56//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: 18, left: 16, bottom: 14, right: 0)
        return textView
    }()

  
    override func createView() {
        setNavBarViewHidden(true)
        
        view.backgroundColor = .clear
        
        contentView.addSubview(InputBarView)
        InputBarView.addSubview(textView)
        InputBarView.addSubview(magnifyBtn)
        InputBarView.addSubview(sendBtn)
        
        InputBarView.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.top.equalTo(12)
            make.bottom.equalTo(-12)
        }
        
        textView.snp.makeConstraints { make in
            make.leading.equalTo(0)
            make.trailing.equalTo(-60)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
            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)
        }
        
        magnifyBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.top.equalTo(16)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }

    }
    
    
    override func dealThings() {
        // 监听文本变化事件
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: UITextView.textDidChangeNotification, object: textView)
        NotificationCenter.default.addObserver(self, selector: #selector(handleAIAnsweringNotification(_:)), name: .kAIAnsweringNotification, object: nil)
    }

    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()
        }
    }
    
    func sendEnabled(enabled:Bool){
        if enabled == true,
           isAIAnswering == false,
           textView.text.replacingOccurrences(of: " ", with: "").count > 0 {
            sendBtn.isEnabled = true
        }else{
            sendBtn.isEnabled = false
        }
    }

    
    func emptyInput() {
        textView.text = ""
        textDidChange()
        magnifyBtn.isHidden = true
    }
    
    
    @objc func handleAIAnsweringNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let boolValue = userInfo[kIsAIAnswering] as? Bool {
            isAIAnswering = boolValue
        }
    }
    
    
    deinit {
        // 移除通知监听
        NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: textView)
    }
}


extension TSChatInputBarVC {

    @objc private func textDidChange() {
        // 计算输入框的内容高度
        let sizeToFit = CGSize(width: textView.bounds.width, height: .greatestFiniteMagnitude)
        let estimatedSize = textView.sizeThatFits(sizeToFit)

        // 根据内容高度调整输入框的高度
        var newHeight = estimatedSize.height
        if newHeight <= minHeight {
            newHeight = minHeight
            textView.isScrollEnabled = false
            magnifyBtn.isHidden = true
        } else if newHeight > maxHeight {
            newHeight = maxHeight
            textView.isScrollEnabled = true
            magnifyBtn.isHidden = false
        } else {
            textView.isScrollEnabled = false
            magnifyBtn.isHidden = true
        }
         
        
        sendEnabled(enabled: textView.text.count > 0)

        // 更新输入框的高度
        textView.snp.updateConstraints { make in
            make.height.equalTo(newHeight)
        }
    }

    private func scrollTextViewToBottom() {
        let bottomOffset = CGPoint(x: 0, y: textView.contentSize.height - textView.bounds.size.height)
        textView.setContentOffset(bottomOffset, animated: true)
    }
    
}


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