//
//
//  SessionInputOperateView.swift

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

import Combine
import UIKit
protocol SessionInputOperateViewDelegate: AnyObject {
    func operateTapGiftAction()
    func operateVoiceAction(on: Bool)
    func operateTapMoreAction()
    func operateTapHelpAction()
    func operateTapInputFieldAction()
}

enum InputOperateState {
    case text
    case voice
}

class SessionInputOperateView: UIView {
    weak var delegate: SessionInputOperateViewDelegate?
    
    var safeView: InputSafeView!
    
    var expandView: SessionPhoneExpandView!
    
    var block: UIView!
    var effectViewOnBlock: UIVisualEffectView!
    var modeButton: UIButton!
    
    var voiceHoldView: UIView!
    
    var inputTextView: CLTextView!
    let minTextViewHeight = 40.0//56.0
    var sendBtn: UIButton!
    var isFirstIn: Bool = true

    //var tapInputFieldAction: (() -> Void)?
    //    var voiceHoldAction: ((_ onVoice: Bool) -> Void)?
    
    /// 当前模式
    @Published var state: InputOperateState = .text
    private var cancellables = Set<AnyCancellable>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = false   // 允许子视图绘制到框外
        self.isUserInteractionEnabled = true
        
        setupViews()
        setupData()
        setupEvent()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // 1. 自身不可见/无交互 → 剪枝
        if alpha <= 0.01 || isHidden || !isUserInteractionEnabled { return nil }
        
        // 2. 自身命中（含子视图）→ 正常返回
        let hit = super.hitTest(point, with: event)
        if hit != nil { return hit }
        
        // 3. 自身没命中，继续测**所有子视图（含超框）**
        for sub in subviews.reversed() {
            let converted = sub.convert(point, from: self)
            return sub.hitTest(converted, with: event)
        }
        return nil
    }
    
    private func setupViews() {
        safeView = {
            let v = InputSafeView()
//            v.backgroundColor = .orange
            addSubview(v)
            v.snp.makeConstraints { make in
                make.left.top.right.equalToSuperview()
                // make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom*0.5-16)
                make.bottom.equalToSuperview()
            }
            return v
        }()
        
        expandView = {
            let v = SessionPhoneExpandView()
            safeView.clipsToBounds = false
            safeView.isUserInteractionEnabled = true

            safeView.addSubview(v)
//            v.backgroundColor = .blue
            v.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(24)
                make.top.equalToSuperview().inset(16).priority(999)
                make.bottom.equalToSuperview().inset(16)
                make.width.height.equalTo(44)
            }
            return v
        }()
        
        block = {
            let v = UIView()
            v.backgroundColor = .c.cseln
            v.cornerRadius = 24
            safeView.addSubview(v)
            v.snp.makeConstraints { make in
                make.left.equalTo(expandView.snp.right).offset(12)
                make.right.equalToSuperview().offset(-20)
//                make.height.equalTo(48)
                make.top.equalToSuperview().inset(16)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        effectViewOnBlock = {
            let v = UIVisualEffectView(effect: UIBlurEffect(style: .light))
            v.alpha = 0.9
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        modeButton = {
            let v = UIButton()
            block.addSubview(v)
            let size = CGSize(width: 26, height: 26)
//            let image = MWIconFont.image(fromIcon: .voiceMsg, size: size, color: .white)
            let image = UIImage(named: "role_chat_voice")
            v.setImage(image, for: .normal)
            v.touchAreaInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            v.addTarget(self, action: #selector(tapModeButton), for: .touchUpInside)
            v.snp.makeConstraints { make in
                make.size.equalTo(size)
                make.left.equalToSuperview().inset(12)
                make.bottom.equalToSuperview().inset(11)
            }
            return v
        }()
        
        sendBtn = {
            let btn = UIButton()
            block.addSubview(btn)
            btn.setImage(UIImage(named: "role_chat_send"), for: .normal)
            btn.addTarget(self, action: #selector(tapSendButton), for: .touchUpInside)
            btn.snp.makeConstraints { make in
                make.bottom.equalToSuperview().inset(2)
                make.right.equalToSuperview().inset(3)
                make.width.equalTo(60)
                make.height.equalTo(44)
            }
            return btn
        }()
        
        inputTextView = {
            let v = CLTextView()
            block.addSubview(v)
            v.placeholder = "Type a message..."
            v.textContainerInset = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 0)
            v.placeholderTextColor = UIColor.init(white: 1, alpha: 0.4)
            v.backgroundColor = .clear
            v.limit.maxCharacterNumber = 500
            v.font = .t.tll
            v.textColor = UIColor.white
            v.font = UIFont.systemFont(ofSize: 14)
            v.snp.makeConstraints { make in
                make.left.equalTo(modeButton.snp.right).offset(10)
                make.right.equalTo(sendBtn.snp.left).offset(-10)
                make.height.equalTo(minTextViewHeight)
                make.centerY.equalToSuperview()
                make.top.equalToSuperview().inset(4)
            }
            return v
        }()
        
        voiceHoldView = {
            let v = UIView()
            block.insertSubview(v, belowSubview: modeButton)
            v.snp.makeConstraints { make in
                make.left.right.top.bottom.equalToSuperview()
//                make.left.right.equalTo(inputTextView)
            }
            
            let voiceImgView = UIImageView(image: UIImage(named: "role_chat_remind_voice"))
            
            let label = UILabel()
            label.font = .t.tll
            label.textColor = .white
            label.textAlignment = .center
            label.text = "Hold to Talk"
            
            let stackView = UIStackView(arrangedSubviews: [voiceImgView, label])
            stackView.spacing = 3
            stackView.alignment = .center
            stackView.distribution = .fill
            v.addSubview(stackView)
            stackView.snp.makeConstraints { make in
                make.centerX.centerY.equalToSuperview()
            }
            
            return v
        }()
    }
    
    private func setupData() {
        state = .text
    }
    
    private func setupEvent() {
        
        inputTextView.textPublisher.sink {[weak self] str in
            self?.fixTextViewHeight()
        }.store(in: &cancellables)
        
        // 添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        longPress.minimumPressDuration = 0.2 // 长按时间，默认 0.5 秒
        voiceHoldView.addGestureRecognizer(longPress)
        
        $state.sink { [weak self] state in
            self?.refreshByState(stateOf: state)
        }.store(in: &cancellables)
        
        
    }
    
    // MARK: - Helper
    
    private func refreshByState(stateOf: InputOperateState) {
//        let size = CGSize(width: 26, height: 26)
        switch stateOf {
        case .text:
            inputTextView.isHidden = false
            voiceHoldView.isHidden = true
            sendBtn.isHidden = false
            let image = UIImage(named: "role_chat_voice")
            modeButton.setImage(image, for: .normal)
            if !isFirstIn {
                self.fixTextViewHeight()
                self.inputTextView.becomeFirstResponder()
            }
        case .voice:
            inputTextView.isHidden = true
            voiceHoldView.isHidden = false
            sendBtn.isHidden = true
            let image = UIImage(named: "role_chat_keyboard")
            modeButton.setImage(image, for: .normal)
            self.inputTextView.snp.updateConstraints { make in
                make.height.equalTo(40)
            }
            self.inputTextView.resignFirstResponder()
            AudioRecordTool.audioAuth()
        }
        
        if isFirstIn {
            isFirstIn = false
        }
    }
    
    private func fixTextViewHeight(){
        if inputTextView.contentSize.height > minTextViewHeight {
            inputTextView.snp.updateConstraints { make in
                let maxH = inputTextView.contentSize.height
                make.height.equalTo(max(maxH >= 173 ? 173 : maxH, 48)) // 73
            }
        }else{
            inputTextView.snp.updateConstraints { make in
                make.height.equalTo(minTextViewHeight) //minTextViewHeight
            }
        }
    }
    
    // MARK: - Action
    
    @objc private func tapGiftButton() {
        delegate?.operateTapGiftAction()
    }
    
    @objc private func tapModeButton() {
        // delegate?.operateTapVoiceAction()
        if state == .text {
            self.state = .voice
        } else {
            self.state = .text
        }
    }
    
    @objc private func tapSendButton() {
        
    }
    
    @objc private func tapMoreButton() {
        delegate?.operateTapMoreAction()
    }
    
    @objc private func tapHelpButton(){
        delegate?.operateTapHelpAction()
    }

    @objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
        switch gesture.state {
        case .began:
            delegate?.operateVoiceAction(on: true)
        case .changed:
            break
        case .ended:
            delegate?.operateVoiceAction(on: false)
        case .cancelled, .failed:
            delegate?.operateVoiceAction(on: false)
        default:
            break
        }
    }
}

extension SessionInputOperateView: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        //dlog("tap fake field")
        //tapInputFieldAction?()
        delegate?.operateTapInputFieldAction()
        return false
    }
}
