package com.example.myapplication

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import android.content.ClipData
import android.content.ClipboardManager
import android.widget.Toast
import androidx.core.widget.NestedScrollView
import de.hdodenhof.circleimageview.CircleImageView
import android.widget.TextView
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.view.WindowManager
import android.graphics.Rect
import android.view.inputmethod.EditorInfo
import android.view.KeyEvent
import androidx.core.content.ContextCompat
import android.widget.ImageView
import android.text.TextWatcher
import android.text.Editable

class GuideActivity : AppCompatActivity() {

    private lateinit var scrollView: NestedScrollView
    private lateinit var listLayout: LinearLayout
    private lateinit var inputMessage: EditText
    private lateinit var btnSend: ImageView
    private lateinit var itemAnim: Animation
    private lateinit var bottomPanel: LinearLayout
    private lateinit var hintLayout: LinearLayout
    private lateinit var titleTextView: TextView

    
    // 我方的预设回复
    private val replyData = listOf(
        "你好",
        "这是第二条消息",
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guide)

        window.setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN or
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
        )

        // 1. 找到控件
        scrollView = findViewById(R.id.scrollView)
        listLayout = findViewById(R.id.message_list)
        inputMessage = findViewById(R.id.input_message)
        btnSend = findViewById(R.id.btn_send)
        bottomPanel = findViewById(R.id.bottom_panel)
        hintLayout = findViewById(R.id.hintLayout)
        titleTextView = findViewById(R.id.title)
        val rootView = findViewById<View>(R.id.rootCoordinator)

        inputMessage.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 不需要实现
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 不需要实现
            }

            override fun afterTextChanged(s: Editable?) {
                hintLayout.visibility =
                    if (s.isNullOrEmpty()) View.VISIBLE else View.GONE
            }
        })
        // 动画
        itemAnim = AnimationUtils.loadAnimation(this, R.anim.item_slide_in_up)
        //自动聚焦
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
        // 自动弹出键盘
        inputMessage.post {
            inputMessage.isFocusable = true
            inputMessage.isFocusableInTouchMode = true
            inputMessage.requestFocus()
    
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(inputMessage, InputMethodManager.SHOW_FORCED)
        }
        // 情话复制
        findViewById<TextView>(R.id.love_words_1).setOnClickListener {
            val text = it as TextView
            val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            clipboard.setPrimaryClip(ClipData.newPlainText("text", text.text))
            Toast.makeText(this, "Copy successfully", Toast.LENGTH_SHORT).show()
        }
        findViewById<TextView>(R.id.love_words_2).setOnClickListener {
            val text = it as TextView
            val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            clipboard.setPrimaryClip(ClipData.newPlainText("text", text.text))
            Toast.makeText(this, "Copy successfully", Toast.LENGTH_SHORT).show()
        }
        // 关闭按钮
        findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
            finish()
        }
        //输入框上移
        rootView.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            // 获取窗口可见区域
            rootView.getWindowVisibleDisplayFrame(r)
        
            val screenHeight = rootView.rootView.height
            val visibleBottom = r.bottom
            val keyboardHeight = screenHeight - visibleBottom
        
            // 这个阈值防止“状态栏/导航栏变化”被误认为键盘
            val isKeyboardVisible = keyboardHeight > screenHeight * 0.15
        
            if (isKeyboardVisible) {
                // 键盘高度为正，把 bottomPanel 抬上去，但不要抬太高
                // 只上移键盘高度减去底部面板高度，让输入框刚好在键盘上方
                val adjustedTranslation = -(keyboardHeight - bottomPanel.height)
                bottomPanel.translationY = adjustedTranslation.toFloat()
        
                // 为了让最后一条消息不被挡住，可以给 scrollView 加个 paddingBottom
                scrollView.setPadding(
                    scrollView.paddingLeft,
                    scrollView.paddingTop,
                    scrollView.paddingRight,
                    keyboardHeight + bottomPanel.height
                )
        
                // 再滚到底，保证能看到最新消息
                scrollToBottom()
            } else {
                // 键盘收起，复位
                bottomPanel.translationY = 0f
                scrollView.setPadding(
                    scrollView.paddingLeft,
                    scrollView.paddingTop,
                    scrollView.paddingRight,
                    bottomPanel.height // 保持底部有一点空隙也可以按你需求调
                )
            }
        }

        // 键盘发送
        inputMessage.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                // 走同一套发送逻辑
                sendMessage()
                true 
            } else {
                false
            }
        }
        
        
        
        // 2. 发送按钮点击事件
        btnSend.setOnClickListener {
            sendMessage()
        }
    }

    fun dp2px(dp: Int): Int {
        return (dp * resources.displayMetrics.density).toInt()
    }
    // 发送消息
    private fun sendMessage() {
        val text = inputMessage.text.toString().trim()

        // 判空，没输入就不发
        if (text.isEmpty()) {
            return
        }

        // 2.1 把“对方”的消息（你刚输入的）显示出来
        addOtherPartyMessage(text)

        // 2.2 清空输入框
        inputMessage.setText("")

        val replyText = replyData.random()
        
        // 保存原来的标题文本
        val originalTitle = titleTextView.text.toString()
        
        // 延迟执行我方回复
        scrollView.postDelayed({
            // 先恢复标题文本
            titleTextView.text = originalTitle
            // 然后添加我方回复
            addOurMessage(replyText)
        }, 1500)
        
        scrollView.postDelayed({
            titleTextView.text = "The other party is typing..."
        }, 500)
        inputMessage.isFocusable = true
        inputMessage.isFocusableInTouchMode = true
    
        inputMessage.post {
            // 重新获取焦点
            inputMessage.requestFocus()
            // 光标移到文本末尾（虽然现在是空的，但习惯性加上）
            inputMessage.setSelection(inputMessage.text.length)
    
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(inputMessage, InputMethodManager.SHOW_IMPLICIT)
        }
    }

    // ======== 渲染“对方”消息：item_other_party_message ========
    private fun addOtherPartyMessage(text: String) {
        // inflate 对方消息布局
        val itemView = layoutInflater.inflate(
            R.layout.item_other_party_message,
            listLayout,
            false
        )

        val avatar = itemView.findViewById<CircleImageView>(R.id.avatar)
        val container = itemView.findViewById<TextView>(R.id.container)

        // 头像（你可以换成对方头像）
        avatar.setImageResource(R.drawable.logo)

        // 显示内容
        container.text = text

        // 加到列表里
        listLayout.addView(itemView)
        itemView.startAnimation(itemAnim)

        // 每加一条就滚动到底
        scrollToBottom()
    }

    // ======== 渲染“我方”消息：item_our_news_message ========
    private fun addOurMessage(text: String) {
        val itemView = layoutInflater.inflate(
            R.layout.item_our_news_message,
            listLayout,
            false
        )

        val avatar = itemView.findViewById<CircleImageView>(R.id.avatar)
        val container = itemView.findViewById<TextView>(R.id.container)

        // 我方头像（随便放一个）
        avatar.setImageResource(R.drawable.logo)

        container.text = text

        listLayout.addView(itemView)
        itemView.startAnimation(itemAnim)

        scrollToBottom()
    }

    // ======== 滚动到底部 ========
    private fun scrollToBottom() {
        scrollView.post {
            scrollView.fullScroll(View.FOCUS_DOWN)
        }
    }
}
