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

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.core.os.bundleOf
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 com.google.android.flexbox.FlexboxLayout
import com.google.android.flexbox.FlexboxLayout.LayoutParams
import kotlinx.coroutines.launch



class SearchFragment : Fragment() {

    private lateinit var historyLayout: FlexboxLayout
    private lateinit var etInput: EditText
    private val prefsName = "search_history"
    private lateinit var historySection: LinearLayout
    private lateinit var recyclerRecommendList: RecyclerView
    private lateinit var themeCardAdapter: ThemeCardAdapter

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

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

        // 推荐主题列表
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val recommendThemeListResp = getrecommendThemeList()?.data
                // 渲染推荐主题列表
                recommendThemeListResp?.let { themes ->
                    themeCardAdapter.submitList(themes)
                }
            } catch (e: Exception) {
                Log.e("SearchFragment", "获取推荐主题列表异常", e)
            }
        }

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


        
        historySection = view.findViewById(R.id.layout_history_section)
        historyLayout = view.findViewById(R.id.layout_history_list)
        etInput = view.findViewById(R.id.et_input)
        recyclerRecommendList = view.findViewById(R.id.recycler_recommend_list)
        
        // 初始化RecyclerView
        setupRecyclerView()

        // 加载历史记录
        loadHistory()

        // 点击 Search 按钮
        val tvSearch = view.findViewById<TextView>(R.id.tv_search)
        tvSearch.setOnClickListener {
            val keyword = etInput.text.toString().trim()
            if (keyword.isNotEmpty()) {
                saveHistory(keyword)
        
                // 把搜索词放进 Bundle
                val bundle = bundleOf("search_keyword" to keyword)
        
                // 跳转时带上 bundle
                findNavController().navigate(
                    R.id.action_searchFragment_to_searchResultFragment,
                    bundle
                )
        
                etInput.setText("")
            } else {
                Toast.makeText(requireContext(), "请输入搜索内容", Toast.LENGTH_SHORT).show()
            }
        }

        // 清空历史记录
        view.findViewById<FrameLayout>(R.id.iv_delete_history).setOnClickListener {
            clearHistory()
        }
    }

    /** 保存历史记录到 SharedPreferences */
    private fun saveHistory(keyword: String) {
        val prefs = requireContext().getSharedPreferences(prefsName, Context.MODE_PRIVATE)
        val oldList = prefs.getStringSet("list", mutableSetOf())!!.toMutableSet()

        oldList.add(keyword)

        prefs.edit().putStringSet("list", oldList).apply()
    }

    /** 加载历史记录 */
    private fun loadHistory() {
        historyLayout.removeAllViews()
    
        val prefs = requireContext().getSharedPreferences(prefsName, Context.MODE_PRIVATE)
        val list = prefs.getStringSet("list", emptySet())?.toList() ?: emptyList()
    
        if (list.isEmpty()) {
            historySection.visibility = View.GONE  // 没有历史 → 隐藏区域
            return
        } else {
            historySection.visibility = View.VISIBLE  // 有历史 → 显示区域
        }
    
        for (item in list.reversed()) {
            historyLayout.addView(createHistoryItem(item))
        }
    }
    
    

    /** 创建历史记录 item */
    private fun createHistoryItem(keyword: String): View {
        val tv = TextView(requireContext())
        tv.text = keyword
        tv.textSize = 11f                        // 字体大小 11sp
        tv.setTextColor(Color.parseColor("#1B1F1A"))
        tv.setPadding(30, 16, 30, 16)
        tv.setBackgroundResource(R.drawable.history_item_bg)
    
        val params = FlexboxLayout.LayoutParams(
            FlexboxLayout.LayoutParams.WRAP_CONTENT,
            FlexboxLayout.LayoutParams.WRAP_CONTENT
        )
        params.setMargins(10, 10, 10, 10)
        tv.layoutParams = params
    
        tv.setOnClickListener {
            etInput.setText(keyword)
            etInput.setSelection(keyword.length)
        }
    
        return tv
    }
    

    /** 清空历史记录 */
    private fun clearHistory() {
        val prefs = requireContext().getSharedPreferences(prefsName, Context.MODE_PRIVATE)
        prefs.edit().clear().apply()
    
        historyLayout.removeAllViews()
        historySection.visibility = View.GONE
    }

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

    private suspend fun getrecommendThemeList(): ApiResponse<List<themeStyle>>? {
        return try {
            RetrofitClient.apiService.recommendThemeList()
        } catch (e: Exception) {
            Log.e("SearchFragment", "获取推荐列表失败", e)
            null
        }
    }
}
    
