//
//  Untitled.swift

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

import UIKit
import Combine
protocol IMInputBarDelegate: AnyObject{
    func albumTapAction()
    func sendTapAction(mesgStr: String, photo: UploadPhotoM?)
    func giftTapAction()
    func helpTapAction()
    func moreTapAction()
}

class SessionInputView: UIView {
    weak var delegate: IMInputBarDelegate?
    
    var block:UIView!
    
    var effectView: UIVisualEffectView!

    var contentStackV: UIStackView!
    var referenceButton: CommonUploadImageButton!
    var textView: CLTextView!

    var leftButtonsStackH: UIStackView!
    var giftButton: EPIconGhostButton!
    var photoButton: EPIconGhostButton!
    
    var rightButtonsStackH: UIStackView!
    var helpButton: EPIconGhostButton!
    var addButton: EPIconGhostButton!
    var sendButtonContainer : UIView!
    var sendButton: EPIconPrimaryButton!
    
    let minTextViewHeight = 40.0//56.0
    
    @Published var uploadImage: UploadPhotoM?
    
    private var cancellables = Set<AnyCancellable>()

    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() {
        backgroundColor = .clear
        
        block = {
            let v = UIView()
            v.cornerRadius = 16
            v.layer.masksToBounds = true
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 24, bottom: 16, right: 24))
            }
            return v
        }()

        effectView = {
            let v = UIVisualEffectView(effect: UIBlurEffect(style: .light))
            v.alpha = 0.9
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        contentStackV = {
            let v = UIStackView()
            v.spacing = 12
            v.axis = .vertical
            v.alignment = .leading
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(12) // 16
            }
            return v
        }()

        referenceButton = {
            let v = CommonUploadImageButton()
            contentStackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(100)
                make.width.equalTo(100)
            }
            v.isHidden = true
            return v
        }()

        textView = {
            let v = CLTextView()
            v.placeholder = "Chat"
            v.backgroundColor = .clear
            v.limit.maxCharacterNumber = 500
            v.font = .t.tll
            v.textColor = .text
            contentStackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(12)
                make.trailing.equalToSuperview().offset(-12)
                make.height.equalTo(minTextViewHeight)
            }
            return v
        }()

        leftButtonsStackH = {
            let v = UIStackView()
            v.spacing = 4
            v.alignment = .center
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(contentStackV.snp.bottom).offset(8)
                make.leading.equalToSuperview().offset(8)
                make.bottom.equalToSuperview().offset(-8)
                make.height.equalTo(40)
            }
            return v
        }()

        giftButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .giftBorder)
            v.addTarget(self, action: #selector(tapGiftButton), for: .touchUpInside)
            leftButtonsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            return v
        }()

        photoButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .iconUploadimg)
            v.addTarget(self, action: #selector(tapPhotoButton), for: .touchUpInside)
            leftButtonsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            return v
        }()

        rightButtonsStackH = {
            let v = UIStackView()
            v.spacing = 4
            v.alignment = .center
            block.addSubview(v)
            v.snp.makeConstraints { make in
                // make.top.equalTo(contentStackV.snp.bottom).offset(8)
                make.centerY.equalTo(leftButtonsStackH)
                make.trailing.equalToSuperview().offset(-8)
                make.height.equalTo(40)
            }
            return v
        }()

        helpButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .prompt)
            v.addTarget(self, action: #selector(tapHelpButton), for: .touchUpInside)
            rightButtonsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            return v
        }()

        addButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .add)
            rightButtonsStackH.addArrangedSubview(v)
            v.addTarget(self, action: #selector(tapAddButton), for: .touchUpInside)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            v.isHidden = true
            return v
        }()
        
        sendButtonContainer = {
            let v = UIView()
            rightButtonsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSizeMake(36, 36))
            }
            return v
        }()
        
        sendButton = {
            let v = EPIconPrimaryButton(radius: .round, iconSize: .small, iconCode: .iconSend)
            v.addTarget(self, action: #selector(tapSendButton), for: .touchUpInside)
            v.isEnabled = true
            sendButtonContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
                make.center.equalToSuperview()
            }
            return v
        }()
    }

    private func setupData() {
    }

    private func setupEvent() {
        
        textView.textPublisher.sink {[weak self] str in
            self?.refreshButtonState()
            self?.fixTextViewHeight()
        }.store(in: &cancellables)
        
        referenceButton.$uploadState.sink {[weak self] state in
            dlog("image uploadstate: \(state)")
            self?.refreshButtonState()
        }.store(in: &cancellables)
        
        referenceButton.closeAction = {[weak self] button in
            self?.uploadImage = nil
            button.givtStateOutsize(.success)
            button.setupImageDefaultState()
            button.isHidden = true
        }
        
        $uploadImage.sink {[weak self] model in
            self?.referenceButton.isHidden = model == nil
            self?.refreshButtonState()
        }.store(in: &cancellables)
    }
    
    // MARK: - Public
    public func fillDefaultContent(string: String){
        textView.text = string
        NotificationCenter.default.post(
            name: UITextView.textDidChangeNotification,
            object: textView)
    }
    

    
    func bindImage(img: UIImage){
        uploadImage = referenceButton.bindViewImage(img, checkImage: true)
        
    }
    
    func clearInputDatas(){
        self.textView.text = ""
        NotificationCenter.default.post(
            name: UITextView.textDidChangeNotification,
            object: textView
        )
        uploadImage = nil
        // cancelFistResponse()
    }
    
    // MARK: - Action
    
    @objc private func tapSendButton(){
        let text = textView.text.trimmed
        
//        #warning("test")
//        let model = UploadPhotoM()
//        model.remoteFullPath = "https://hhb.crushlevel.ai/static/img/dfhig.jpg"
//        model.isAutoCheckImage = false
//        model.addThisItemTimeStamp = Date().timeStamp
//        model.imageSize = CGSize(width: 200, height: 300)
//        uploadImage = model
        
        delegate?.sendTapAction(mesgStr: text, photo: uploadImage)
    }
    
    @objc private func tapGiftButton(){
        delegate?.giftTapAction()
    }
    
    @objc private func tapPhotoButton(){
        delegate?.albumTapAction()
    }
    
    @objc private func tapHelpButton(){
        delegate?.helpTapAction()
    }
    
    @objc private func tapAddButton(){
        delegate?.moreTapAction()
    }
    
    // MARK: - Helper
    
    private func fixTextViewHeight(){
        if textView.contentSize.height > minTextViewHeight{
            textView.snp.updateConstraints { make in
                make.height.equalTo(75) // 73
            }
        }else{
            textView.snp.updateConstraints { make in
                make.height.equalTo(textView.contentSize.height) //minTextViewHeight
            }
        }
    }
    
    private func refreshButtonState(){
        // 文本发送是必须的！
        let textCheckOK = (textView.text.trimmed).count > 0
        
        addButton.isHidden = textCheckOK
        sendButtonContainer.isHidden = !textCheckOK
        
        var imageCheckOK = true
        if let img = uploadImage{
            imageCheckOK = false
            if let imageUrl = img.remoteFullPath, imageUrl.count > 0, (img.imageChecked && img.imageCheckIsViolation == false){
                imageCheckOK = true
            }
        }
        sendButton.isEnabled = textCheckOK && imageCheckOK
    }
    
    public func cancelFistResponse() {
        self.endEditing(true)
    }
    
    @discardableResult
    override func becomeFirstResponder() -> Bool {
        self.textView.becomeFirstResponder()
    }
    
    public func becomeFistResponse() {
        self.textView.becomeFirstResponder()
    }
    
    public func isFistReponse() -> Bool {
        return textView.isFirstResponder
    }
    
   
}
