package com.app.wave.keyboard.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.app.wave.keyboard.App
import com.app.wave.keyboard.R
import com.app.wave.keyboard.bean.DetailsBean
import com.app.wave.keyboard.databinding.FragmentCollectionBinding
import com.app.wave.keyboard.database.BaseDB
import com.app.wave.keyboard.database.DBManager
import com.app.wave.keyboard.callback.RemoveCallback
import com.app.wave.keyboard.adapter.CollectionAdapter
import kotlinx.coroutines.launch

class CollectionFragment : Fragment() {

    private lateinit var vb: FragmentCollectionBinding
    private lateinit var adapter: CollectionAdapter

    companion object {
        @JvmStatic
        fun newInstance() = CollectionFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        vb = FragmentCollectionBinding.inflate(inflater, container, false)
        return vb.root
    }

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

    private fun init() {
        // 初始化适配器
        adapter = CollectionAdapter(requireContext()).apply {
            setRemoveLike(object : RemoveCallback {
                override fun OnRemoveLike(data: DetailsBean) {
                    lifecycleScope.launch {
                        DBManager.removeLike(data)
                        // 简单提示
                        android.widget.Toast.makeText(
                            requireContext(),
                            "Removed from favorites",
                            android.widget.Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })
        }

        // 设置RecyclerView
        vb.likeRecycler.run {
            adapter = this@CollectionFragment.adapter
            layoutManager = GridLayoutManager(requireContext(), 2)
        }

        // 观察收藏数据变化
        BaseDB.baseDB.ThemesDao().queryAllLike().observe(viewLifecycleOwner) { favoriteList ->
            Log.d(App.TAG, "Collection size: ${favoriteList?.size}")

            if (favoriteList.isNullOrEmpty()) {
                // 显示空状态
                showEmptyState()
            } else {
                // 显示收藏列表
                showCollectionList(favoriteList as List<DetailsBean>)

                // 更新收藏数量显示
                updateFavoriteCountDisplay(favoriteList.size)
            }
        }
    }

    private fun showEmptyState() {
        // 隐藏收藏列表
        vb.likeRecycler.visibility = View.GONE

        // 隐藏收藏数量显示
        vb.textFavoriteCountContainer.visibility = View.GONE

        // 显示空状态布局
        val emptyContainer = vb.root.findViewById<View>(R.id.empty_container)
        emptyContainer?.visibility = View.VISIBLE

    }

    private fun showCollectionList(favoriteList: List<DetailsBean>) {
        // 显示收藏列表
        vb.likeRecycler.visibility = View.VISIBLE

        // 隐藏空状态
        val emptyContainer = vb.root.findViewById<View>(R.id.empty_container)
        emptyContainer?.visibility = View.GONE

        // 更新适配器数据
        adapter.setForYouList(favoriteList)
    }

    private fun updateFavoriteCountDisplay(count: Int) {
        if (count > 0) {
            // 显示收藏数量容器
            vb.textFavoriteCountContainer.visibility = View.VISIBLE

            // 更新数量文本
            val countText = when (count) {
                1 -> "1 keyboard collected"
                else -> "$count keyboards collected"
            }
            vb.textFavoriteCount.text = countText
        } else {
            // 隐藏收藏数量容器
            vb.textFavoriteCountContainer.visibility = View.GONE
        }
    }
}