package com.example.wallisyn.Activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.example.wallisyn.R
import com.example.wallisyn.connector.OnItemClick
import com.example.wallisyn.databinding.ActivityWallpaperSearchBinding
import com.example.wallisyn.item.ListWallpaperItem
import com.example.wallisyn.mybean.MyData
import com.example.wallisyn.tool.ComUtils
import com.example.wallisyn.tool.ItemHelper
import com.example.wallisyn.tool.ObectBoxManager

class WallpaperSearchActivity : AppCompatActivity(), OnItemClick {
    private var adapterWallapper: ListWallpaperItem? = null
    private var binding: ActivityWallpaperSearchBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 全局异常捕获（避免布局绑定/初始化失败崩溃）
        try {
            binding = ActivityWallpaperSearchBinding.inflate(getLayoutInflater())
            setContentView(binding!!.getRoot())
            ComUtils.initFull(this, false)
            initList()
            initKeywordsClick()
            initBackClick()
        } catch (e: Exception) {
            Toast.makeText(this, "搜索页面加载失败", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
            finish() // 避免卡死在空白页
        }
    }

    private fun initList() {
        val height = ComUtils.dp2Px(180)
        // 适配器初始化容错（避免Context传递异常）
        adapterWallapper = ListWallpaperItem(this, height, true)
        adapterWallapper!!.setInfoWallpaperListener(this)

        // RecyclerView 配置（添加空安全）
        val recyclerItemHelper = ItemHelper(10, 10, 15)
        val gridLayoutManager = GridLayoutManager(this, 2)

        if (binding!!.resultRecycler != null) {
            binding!!.resultRecycler.setLayoutManager(gridLayoutManager)
            binding!!.resultRecycler.addItemDecoration(recyclerItemHelper)
            binding!!.resultRecycler.setAdapter(adapterWallapper)
        }

        // 搜索框回车触发搜索
        if (binding!!.et != null) {
            binding!!.et.setOnEditorActionListener({ v, actionId, event ->
                if (actionId === EditorInfo.IME_ACTION_SEARCH) {
                    startSearch()
                    return@setOnEditorActionListener true
                }
                false
            })
        }

        // 搜索按钮点击触发
        if (binding!!.btnSearch != null) {
            binding!!.btnSearch.setOnClickListener({ v -> startSearch() })
        }
    }

    // 关键词标签点击事件
    private fun initKeywordsClick() {
        val keywordClickListener = View.OnClickListener { view: View? ->
            if (view is TextView) {
                val keyword = view.getText().toString()
                if (binding!!.et != null) {
                    binding!!.et.setText(keyword)
                    binding!!.et.setSelection(keyword.length) // 光标移到末尾
                }
                startSearch()
            }
        }

        // 给关键词标签设置点击事件（确保布局中存在这些ID）
        if (binding!!.keyword1 != null) binding!!.keyword1.setOnClickListener(keywordClickListener)
        if (binding!!.keyword2 != null) binding!!.keyword2.setOnClickListener(keywordClickListener)
        if (binding!!.keyword3 != null) binding!!.keyword3.setOnClickListener(keywordClickListener)
        if (binding!!.keyword4 != null) binding!!.keyword4.setOnClickListener(keywordClickListener)
        if (binding!!.keyword5 != null) binding!!.keyword5.setOnClickListener(keywordClickListener)
    }

    // 返回按钮点击事件（单独抽离，便于维护）
    private fun initBackClick() {
        if (binding!!.imageviewBack != null) {
            binding!!.imageviewBack.setOnClickListener({ v -> finish() })
        }
    }

    // 关闭软键盘
    private fun closeKeyboard() {
        if (binding!!.et != null) {
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(binding!!.et.getWindowToken(), 0)
        }
    }

    // 搜索核心逻辑
    private fun startSearch() {
        closeKeyboard()
        // 加载中进度条显示（空安全）
        if (binding!!.searchPb != null) {
            binding!!.searchPb.setVisibility(View.VISIBLE)
        }

        // 搜索关键词校验
        val keyword = if (binding!!.et != null) binding!!.et.getText().toString().trim() else ""
        if (keyword.isEmpty()) {
            if (binding!!.searchPb != null) {
                binding!!.searchPb.setVisibility(View.GONE)
            }
            Toast.makeText(this, getString(R.string.please_input_keyword), Toast.LENGTH_SHORT)
                .show()
            return
        }

        // 数据库搜索+结果展示
        Thread(Runnable {
            try {
                // 子线程执行数据库查询（避免主线程阻塞）
                val searchResult = ObectBoxManager.search(keyword)
                // 主线程更新UI
                runOnUiThread(Runnable {
                    if (binding!!.searchPb != null) {
                        binding!!.searchPb.setVisibility(View.GONE)
                    }
                    if (searchResult.size > 0) {
                        showEmpty(false)
                        adapterWallapper!!.setDataInfo(searchResult)
                    } else {
                        showEmpty(true)
                    }
                })
            } catch (e: Exception) {
                runOnUiThread(Runnable {
                    if (binding!!.searchPb != null) {
                        binding!!.searchPb.setVisibility(View.GONE)
                    }
                    showEmpty(true)
                    Toast.makeText(
                        this@WallpaperSearchActivity,
                        "搜索失败，请重试",
                        Toast.LENGTH_SHORT
                    ).show()
                })
                e.printStackTrace()
            }
        }).start()
    }

    // 空结果展示切换
    private fun showEmpty(showEmpty: Boolean) {
        if (binding!!.emptyLayout != null && binding!!.resultRecycler != null) {
            binding!!.emptyLayout.setVisibility(if (showEmpty) View.VISIBLE else View.GONE)
            binding!!.resultRecycler.setVisibility(if (showEmpty) View.GONE else View.VISIBLE)
        }
    }

    // 列表项点击跳转详情页
    override fun onItemClickAction(info: MyData?) {
        try {
            // 校验MyData非空（避免传递空数据崩溃）
            if (info == null) {
                Toast.makeText(this, "壁纸信息异常", Toast.LENGTH_SHORT).show()
                return
            }
            val intent = Intent(this, WallpaperActivity::class.java)
            intent.putExtra(ComUtils.key_info, info) // 确保MyData实现了Serializable/Parcelable
            startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(this, "跳转详情页失败", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
}