package com.app.brush.guitar.ink.eraser

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.app.brush.guitar.ink.App
import com.app.brush.guitar.ink.databinding.CoolActivitySearchKeyboardBinding
import com.app.brush.guitar.ink.drama.DichotomyDetails
import com.app.brush.guitar.ink.gallery.HomeChildGalvanize
import com.app.brush.guitar.ink.iguana.ListDecorationFossil

class SearchTrajectory : AppCompatActivity() {

    private lateinit var vb: CoolActivitySearchKeyboardBinding
    private lateinit var adapter: HomeChildGalvanize
    private val allKeyboards = mutableListOf<DichotomyDetails>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = CoolActivitySearchKeyboardBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(vb.root)
        
        ViewCompat.setOnApplyWindowInsetsListener(vb.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initAllKeyboards()
        setupViews()
    }

    private fun initAllKeyboards() {
        // 从所有分类中收集所有键盘
        allKeyboards.clear()
        App.Companion.list.forEach { wrapper ->
            wrapper.keyboardList?.let { keyboardList ->
                allKeyboards.addAll(keyboardList)
            }
        }
    }

    private fun setupViews() {
        // 返回按钮
        vb.ivBack.setOnClickListener {
            finish()
        }

        // 搜索框
        vb.etSearch.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?) {
                val query = s?.toString()?.trim() ?: ""
                vb.ivClear.visibility = if (query.isNotEmpty()) View.VISIBLE else View.GONE
                performSearch(query)
            }
        })

        // 搜索按钮
        vb.etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = vb.etSearch.text.toString().trim()
                performSearch(query)
                true
            } else {
                false
            }
        }

        // 清除按钮
        vb.ivClear.setOnClickListener {
            vb.etSearch.setText("")
            vb.etSearch.requestFocus()
        }

        // 初始化RecyclerView
        adapter = HomeChildGalvanize(this, emptyList())
        vb.recyclerSearch.layoutManager = GridLayoutManager(this, 2)
        vb.recyclerSearch.adapter = adapter
        vb.recyclerSearch.addItemDecoration(ListDecorationFossil(7, 14, 0))
        
        // 搜索框点击事件 - 显示键盘
        vb.etSearch.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                showKeyboard()
            }
        }
        
        // 搜索框点击事件
        vb.layoutSearchBox.setOnClickListener {
            vb.etSearch.requestFocus()
            showKeyboard()
        }
        
        // 自动聚焦搜索框并显示键盘
        vb.etSearch.post {
            vb.etSearch.requestFocus()
            showKeyboard()
        }
    }
    
    private fun showKeyboard() {
        val imm = getSystemService(InputMethodManager::class.java)
        Handler(Looper.getMainLooper()).postDelayed({
            imm.showSoftInput(vb.etSearch, InputMethodManager.SHOW_IMPLICIT)
        }, 100)
    }

    private fun performSearch(query: String) {
        val results = if (query.isEmpty()) {
            emptyList()
        } else {
            // 支持多个关键词搜索（空格分隔）
            val keywords = query.split(" ").filter { it.isNotBlank() }
            
            allKeyboards.filter { keyboard ->
                val titleName = keyboard.titleName?.lowercase() ?: ""
                
                // 获取该键盘所属的分类名称
                val categoryName = App.list.firstOrNull { wrapper ->
                    wrapper.keyboardList?.contains(keyboard) == true
                }?.parentName?.lowercase() ?: ""

                // 检查是否匹配任何关键词
                keywords.any { keyword ->
                    val lowerKeyword = keyword.lowercase()
                    titleName.contains(lowerKeyword) || categoryName.contains(lowerKeyword)
                }
            }
        }

        adapter = HomeChildGalvanize(this, results)
        vb.recyclerSearch.adapter = adapter

        // 显示/隐藏不同状态
        if (query.isEmpty()) {
            // 初始状态：显示提示
            vb.layoutInitial.visibility = View.VISIBLE
            vb.layoutEmpty.visibility = View.GONE
            vb.recyclerSearch.visibility = View.GONE
        } else if (results.isEmpty()) {
            // 无结果状态
            vb.layoutInitial.visibility = View.GONE
            vb.layoutEmpty.visibility = View.VISIBLE
            vb.recyclerSearch.visibility = View.GONE
        } else {
            // 有结果状态
            vb.layoutInitial.visibility = View.GONE
            vb.layoutEmpty.visibility = View.GONE
            vb.recyclerSearch.visibility = View.VISIBLE
        }
    }
}

