//
//  YHAITextInputView.swift
//  galaxy
//
//  Created by Dufet on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Lottie
import IQKeyboardManagerSwift

enum YHAITextInputStatus: Int {
    case enableSend = 0
    case disableSend = 1
    case loading = 2
}

class YHAITextInputView: UIView {

    let bgColor = UIColor.init(hex: 0xF8FCFF)
    var sendBlock: ((String)->())?
    var stopSendBlock: (()->())?
    var keyBoardChangeBlock: ((_ isShow: Bool)->())?
    var disable: Bool = false
    
    var status: YHAITextInputStatus = .enableSend {
        didSet {
            if status == .enableSend {
                sendBtn.alpha = 1.0
                sendBtn.isEnabled = true
                sendBtn.isHidden = false
                loadingImgView.isHidden = true

                
            } else if status == .disableSend {
                sendBtn.alpha = 0.3
                sendBtn.isEnabled = false
                sendBtn.isHidden = false
                loadingImgView.isHidden = true
                
            } else if status == .loading {
                sendBtn.isHidden = true
                loadingImgView.isHidden = false
            }
        }
    }
    lazy var contentView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.layer.cornerRadius = 12.0
        v.clipsToBounds = true
        return v
    }()
    
    lazy var whiteView: UIView = {
        let v = UIView()
        return v
    }()
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "ai_chat_send"), for: .normal)
        btn.addTarget(self, action: #selector(didSendButtonClicked), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var loadingImgView: LottieAnimationView! = {
        let lottieView = LottieAnimationView(name: "ai_chat_input_pause")
        lottieView.loopMode = .loop
        lottieView.contentMode = .scaleAspectFit
        lottieView.play()
        lottieView.isHidden = true
        let btn = UIButton(type: .custom)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        btn.addTarget(self, action: #selector(didStopSendBtnClicked), for: .touchUpInside)
        lottieView.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return lottieView
    }()
    
    lazy var shadowView: YHAIChatInputShadowView = {
        let v = YHAIChatInputShadowView()
        return v
    }()
    
    @objc func didSendButtonClicked() {
        sendBlock?(textView.text)
        status = .loading
        textView.text = ""
        textView.isScrollEnabled = false
        self.endEditing(true)
        textLabel.isHidden = true
        textView.isHidden = false
    }
    
    @objc func didStopSendBtnClicked() {
        stopSendBlock?()
    }
    
    lazy var textView: YHAutoTextView = {
        let v = YHAutoTextView()
        v.backgroundColor = .clear
        v.font = .PFSC_R(ofSize: 14)
        v.textColor = .mainTextColor
        v.placeHolder = "有什么问题尽管问我"
        v.textChange = {
            [weak self] text in
            guard let self = self else { return }
            self.textLabel.text = text
            if status != .loading {
                status = text.count > 0 ? .enableSend : .disableSend
            }
        }
        return v
    }()
    
    lazy var textLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .mainTextColor
        label.font = .PFSC_R(ofSize: 14)
        label.isHidden = true
        label.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapText))
        label.addGestureRecognizer(tap)
        return label
    }()
    
    @objc func tapText() {
        textView.becomeFirstResponder()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    deinit {
        self.removeNotify()
    }
    
    func addKeyBoardNotify() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    func showKeyBoard(_ isShow: Bool) {
        if isShow {
            self.textView.becomeFirstResponder()
        } else {
            self.textView.resignFirstResponder()
            self.textView.endEditing(true)
        }
    }
    
    func createUI() {
        
        self.backgroundColor = self.bgColor
        self.addSubview(whiteView)
        whiteView.addSubview(shadowView)
        whiteView.addSubview(contentView)
        contentView.addSubview(sendBtn)
        contentView.addSubview(loadingImgView)
        contentView.addSubview(textView)
        contentView.addSubview(textLabel)
        status = .disableSend
        
        whiteView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(10)
            make.bottom.equalTo(-10-k_Height_safeAreaInsetsBottom())
            make.right.equalTo(-20)
        }
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalTo(contentView)
        }
        
        sendBtn.snp.makeConstraints { make in
            make.width.equalTo(24)
            make.height.equalTo(24)
            make.right.equalTo(-16)
            make.bottom.equalTo(-10)
        }
        
        loadingImgView.snp.makeConstraints { make in
            make.edges.equalTo(sendBtn)
        }

        textView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(11-YHAutoTextView.verticalGap)
            make.height.equalTo(30)
            make.bottom.equalTo(-(11-YHAutoTextView.verticalGap))
            make.right.equalTo(sendBtn.snp.left).offset(-5)
        }
        
        textLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.left.equalTo(textView).offset(5)
            make.right.equalTo(textView).offset(-5)
        }
        addKeyBoardNotify()
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if disable {
            return
        }
        if notification.userInfo != nil {
                        
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }

            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : 0)

            if isKeyboardShow {
                textLabel.isHidden = true
                textView.isHidden = false
            } else {
                textLabel.isHidden = textView.text.isEmpty
                textView.isHidden = !textView.text.isEmpty
            }
            textLabel.text = textView.text
            
            textView.isShowKeyboard = isKeyboardShow
            contentView.snp.updateConstraints { make in
                make.bottom.equalTo(-10-(isKeyboardShow ? 0.0 : k_Height_safeAreaInsetsBottom()))
            }

            self.snp.updateConstraints { make in
                make.bottom.equalTo(bottomMargin)
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
            
            keyBoardChangeBlock?(isKeyboardShow)
        }
    }
}
