//
//  SpeakSendMsgBox.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/11.
//

import UIKit

class SpeakResizableTextView: UIView {
    // MARK: - 公开属性
    /// 文本内容
    @IBInspectable var text: String? {
        get { return textView.text }
        set { textView.text = newValue }
    }
    
    /// 占位符文本
    @IBInspectable var placeholder: String? {
        get { return placeholderLabel.text }
        set { placeholderLabel.text = newValue }
    }
    
    /// 占位符颜色
    @IBInspectable var placeholderColor: UIColor = .lightGray {
        didSet { placeholderLabel.textColor = placeholderColor }
    }
    
    /// 文本颜色
    @IBInspectable  var textColor: UIColor? {
        get { return textView.textColor }
        set { textView.textColor = newValue }
    }
    
    /// 字体
    var font: UIFont? {
        get { return textView.font }
        set { textView.font = newValue }
    }
    
    /// 最大行数限制（0 表示无限制）
    @IBInspectable var maxLines: Int = 0 {
        didSet { updateMaxHeight() }
    }
    
    /// 文本变化回调
    var onTextChanged: ((String) -> Void)?
    
    /// 达到最大行数回调
    var onReachMaxLines: (() -> Void)?
    
    // MARK: - 私有属性
    private let textView = UITextView()
    private let placeholderLabel = UILabel()
    private var maxHeight: CGFloat = .greatestFiniteMagnitude
    private var originalInset: UIEdgeInsets?
    
    @discardableResult
    override func becomeFirstResponder() -> Bool {
        self.textView.becomeFirstResponder()
    }
    
    @discardableResult
    override func resignFirstResponder() -> Bool {
        self.textView.resignFirstResponder()
    }
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
        setupConstraints()
    }
    
    // MARK: - 视图设置
    private func setupViews() {
        // 设置背景和边框
        backgroundColor = .white
        layer.cornerRadius = 8
        layer.borderWidth = 1
        layer.borderColor = UIColor.lightGray.cgColor
        
        // 配置 UITextView
        textView.delegate = self
        textView.isScrollEnabled = false
        textView.backgroundColor = .clear
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        textView.keyboardDismissMode = .onDrag
        textView.returnKeyType = .send
        addSubview(textView)
        
        // 配置占位符标签
        placeholderLabel.textColor = placeholderColor
        placeholderLabel.font = textView.font
        placeholderLabel.numberOfLines = 0
        placeholderLabel.isUserInteractionEnabled = false
        addSubview(placeholderLabel)
    }
    
    private func setupConstraints() {
        textView.translatesAutoresizingMaskIntoConstraints = false
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        textView.snp.makeConstraints { make in
            make.left.top.bottom.right.equalToSuperview().inset(UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4))
            make.height.greaterThanOrEqualTo(30)
        }
        placeholderLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview().inset(8)
            make.left.equalToSuperview().inset(16)
        }
    }
    
    // MARK: - 高度计算和更新
    private func updateHeight() {
        let size = CGSize(width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right,
                          height: .greatestFiniteMagnitude)
        let estimatedSize = textView.sizeThatFits(size)
        let newHeight = min(estimatedSize.height, maxHeight)
        var frame = self.frame
        frame.size.height = newHeight
        self.frame = frame
        placeholderLabel.isHidden = !textView.text.isEmpty
        onTextChanged?(textView.text)
    }
    
    private func updateMaxHeight() {
        if maxLines > 0, let font = textView.font {
            let lineHeight = font.lineHeight
            maxHeight = lineHeight * CGFloat(maxLines) + textView.textContainerInset.top + textView.textContainerInset.bottom
        } else {
            maxHeight = .greatestFiniteMagnitude
        }
    }
    
    private func findScrollView() -> UIScrollView? {
        var view: UIView? = self
        while let superview = view?.superview {
            if let scrollView = superview as? UIScrollView {
                if originalInset == nil {
                    originalInset = scrollView.contentInset
                }
                return scrollView
            }
            view = superview
        }
        return nil
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - UITextViewDelegate
extension SpeakResizableTextView : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        updateHeight()
        if maxLines > 0 {
            let size = CGSize(width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right,
                              height: .greatestFiniteMagnitude)
            let estimatedSize = textView.sizeThatFits(size)
            if estimatedSize.height >= maxHeight {
                onReachMaxLines?()
            }
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.returnKeyType == .send {
            if text == "\n" {
                if let callblack = callblack {
                    callblack("")
                }
                return false
            }
        }
        return true
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
}
