package com.example.myapplication.ui.shop.search

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.themeStyle
import com.example.myapplication.ui.shop.ThemeCardAdapter
import kotlinx.coroutines.launch

class SearchResultFragment : Fragment() {

    private lateinit var etInput: EditText
    private lateinit var recyclerSearchResults: RecyclerView
    private lateinit var themeCardAdapter: ThemeCardAdapter
    private lateinit var tvSearch: TextView
    private lateinit var llNoSearchResult: LinearLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_search_result, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 返回按钮
        view.findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
            parentFragmentManager.popBackStack()
        }

        etInput = view.findViewById(R.id.et_input)
        recyclerSearchResults = view.findViewById(R.id.recycler_search_results)
        tvSearch = view.findViewById<TextView>(R.id.tv_search)
        llNoSearchResult = view.findViewById(R.id.ll_no_search_result)
        // 初始化RecyclerView
        setupRecyclerView()

        // 设置搜索按钮点击事件
        tvSearch.setOnClickListener {
            val keyword = etInput.text.toString()
            if (keyword.isEmpty()) {
                Toast.makeText(requireContext(), "请输入搜索词", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            viewLifecycleOwner.lifecycleScope.launch {
                try {
                    val searchResults = getSearchTheme(keyword)?.data
                    // 渲染搜索结果列表
                    handleSearchResults(searchResults)
                } catch (e: Exception) {
                    Log.e("SearchResultFragment", "搜索主题失败", e)
                }
            }
        }
        

        // 接收从上一个页面传来的搜索词
        val keyword = arguments?.getString("search_keyword") ?: ""
        etInput.setText(keyword)
        etInput.setSelection(keyword.length)

        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val searchResults = getSearchTheme(keyword)?.data
                // 渲染搜索结果列表
                handleSearchResults(searchResults)
            } catch (e: Exception) {
                Log.e("SearchResultFragment", "搜索主题失败", e)
            }
        }
    }

    private fun handleSearchResults(themes: List<themeStyle>?) {
        if (themes.isNullOrEmpty()) {
            // 显示无结果提示，隐藏列表
            llNoSearchResult.visibility = View.VISIBLE
            recyclerSearchResults.visibility = View.GONE
        } else {
            // 显示列表，隐藏无结果提示
            llNoSearchResult.visibility = View.GONE
            recyclerSearchResults.visibility = View.VISIBLE
            themeCardAdapter.submitList(themes)
        }
    }

    private suspend fun getSearchTheme(keyword: String): ApiResponse<List<themeStyle>>? {
        return try {
            RetrofitClient.apiService.searchTheme(keyword)
        } catch (e: Exception) {
            Log.e("SearchResultFragment", "搜索主题失败", e)
            null
        }
    }

    private fun setupRecyclerView() {
        // 设置GridLayoutManager，每行显示2个item
        val layoutManager = GridLayoutManager(requireContext(), 2)
        recyclerSearchResults.layoutManager = layoutManager
        
        // 初始化ThemeCardAdapter
        themeCardAdapter = ThemeCardAdapter()
        recyclerSearchResults.adapter = themeCardAdapter
        
        // 设置item间距（可选）
        recyclerSearchResults.setPadding(0, 0, 0, 0)
    }
}
