package com.app.input.breeze.board.uiactivity

import android.os.Bundle
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.app.input.breeze.board.bean.KeyboardTheme
import com.app.input.breeze.board.database.AppDatabase
import com.app.input.breeze.board.database.FavoriteRepository
import com.app.input.breeze.board.databinding.FavoriteActivityBinding
import com.app.input.breeze.board.listutils.FavoriteThemeAdapter
import kotlinx.coroutines.launch

class FavoriteThemeActivity : AppCompatActivity() {

    private lateinit var vb: FavoriteActivityBinding
    private lateinit var FavoriteThemeAdapter: FavoriteThemeAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = FavoriteActivityBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(vb.root)
        TPAdManager.loadAllAd(this)
        showTPAD(this) { }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        setupRecyclerView()
        observeFavorites()
        setupClickListeners()
    }

    private fun setupRecyclerView() {
        FavoriteThemeAdapter = FavoriteThemeAdapter(this).apply {
            setRemoveLike(object : com.app.input.breeze.board.callback.RemoveFavoriteCallback {
                override fun OnRemoveLike(data: KeyboardTheme) {
                    lifecycleScope.launch {
                        FavoriteRepository.removeLike(data)
                    }
                }
            })
        }
        vb.likeRecycler.apply {
            adapter = FavoriteThemeAdapter
            layoutManager = GridLayoutManager(this@FavoriteThemeActivity, 2)
        }
    }

    private fun observeFavorites() {
        AppDatabase.instance.favoriteThemeDao().queryAllLike().observe(this) { favorites ->
            if (favorites.isNullOrEmpty()) {
                vb.likeRecycler.visibility = android.view.View.GONE
                vb.emptyTitle.visibility = android.view.View.VISIBLE
            } else {
                vb.likeRecycler.visibility = android.view.View.VISIBLE
                vb.emptyTitle.visibility = android.view.View.GONE
                FavoriteThemeAdapter.setForYouList(favorites)
            }
        }
    }

    private fun setupClickListeners() {
        vb.back.setOnClickListener {
            finish()
        }
    }
}

