package com.rainbow.app.keyboard.uiactivity

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.ad.tradpluslibrary.TPAdManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.rainbow.app.keyboard.App
import com.rainbow.app.keyboard.R
import com.rainbow.app.keyboard.myadapter.KBItemAdapter
import com.rainbow.app.keyboard.javabean.DetailsjavaBean
import com.rainbow.app.keyboard.mycallback.DeleteCallback
import com.rainbow.app.keyboard.mydb.DatabBase
import com.rainbow.app.keyboard.mydb.DatabManager
import com.rainbow.app.keyboard.databinding.ActivityCollectionBinding
import kotlinx.coroutines.launch

class CollectionActivity : AppCompatActivity() {

    private lateinit var binding: ActivityCollectionBinding
    private lateinit var adapter: KBItemAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCollectionBinding.inflate(layoutInflater)
        this.enableEdgeToEdge()
        TPAdManager.loadAllAd(this)
        setContentView(binding.getRoot())
        showTPAD(this) { }
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v: View, insets: WindowInsetsCompat ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            val topPadding = systemBars.top
            v.setPadding(systemBars.left, topPadding, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()
        initData()
    }

    private fun initViews() {
         binding.back.setOnClickListener {
             showTPAD(this) {
                 finish()
             }

         }
    }

    private fun initData() {
        // 初始化适配器
        adapter = KBItemAdapter(this).apply {
            setShowFavoriteIcon(true)
            applyCollectionConfig()
            setRemoveCallback(object : DeleteCallback {
                override fun OnRemoveLike(data: DetailsjavaBean) {
                    lifecycleScope.launch {
                        DatabManager.removeLike(data)
                        // 从列表中移除该项
                        removeItemFromAdapter(data)

                        android.widget.Toast.makeText(
                            this@CollectionActivity,
                            "Removed from favorites",
                            android.widget.Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })
        }

        // 设置RecyclerView
        binding.likeRecycler.run {
            adapter = this@CollectionActivity.adapter
            layoutManager = GridLayoutManager(this@CollectionActivity, 2)
            clipToPadding = false
            setPadding(0, 0, 0, 0)
        }

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

            if (favoriteList.isNullOrEmpty()) {
                showEmptyState()
            } else {
                showCollectionList(favoriteList as List<DetailsjavaBean>)
                updateFavoriteCountDisplay(favoriteList.size)
            }
        }
    }

    private fun showEmptyState() {
        binding.likeRecycler.visibility = View.GONE
        binding.textFavoriteCountContainer.visibility = View.GONE

        val emptyContainer = findViewById<View>(R.id.empty_container)
        emptyContainer?.visibility = View.VISIBLE
    }

    private fun showCollectionList(favoriteList: List<DetailsjavaBean>) {
        binding.likeRecycler.visibility = View.VISIBLE

        val emptyContainer = findViewById<View>(R.id.empty_container)
        emptyContainer?.visibility = View.GONE

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

    private fun updateFavoriteCountDisplay(count: Int) {
        if (count > 0) {
            binding.textFavoriteCountContainer.visibility = View.VISIBLE
            val countText = when (count) {
                1 -> "1 keyboard collected"
                else -> "$count keyboards collected"
            }
            binding.textFavoriteCount.text = countText
        } else {
            binding.textFavoriteCountContainer.visibility = View.GONE
        }
    }

    // 从适配器中移除指定项
    private fun removeItemFromAdapter(bean: DetailsjavaBean) {
        val position = adapter.getPositionOfItem(bean)
        if (position != -1) {
            adapter.removeItem(position)
        }
    }
}