package com.app.input.personalised.board.boartfragment

import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.input.personalised.board.BoartApp
import com.app.input.personalised.board.databinding.FragmentFavoriteBinding
import com.app.input.personalised.board.basedata.AppDatabase
import com.app.input.personalised.board.listhelpers.FavoriteCardListAdapter

class MyFragment : Fragment() {
    private lateinit var vb: FragmentFavoriteBinding
    private lateinit var favoriteCardListAdapter: FavoriteCardListAdapter

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

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

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

    private fun initFavoriteCards() {
        favoriteCardListAdapter = FavoriteCardListAdapter(requireContext())

        vb.favoriteCardRecycler.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = favoriteCardListAdapter
            setHasFixedSize(false)
            isNestedScrollingEnabled = false
        }

        // 观察收藏数据变化
        AppDatabase.Companion.boartAppDatabase.ThemesDao().queryAllLike().observe(requireActivity()) { favoriteList ->
            Log.d(BoartApp.Companion.TAG, "Favorite data changed, count: ${favoriteList?.size}")
            val filteredList = favoriteList?.filterNotNull() ?: emptyList()
            // 卡片始终显示，将收藏列表传递给适配器（可能为空）
            favoriteCardListAdapter.setFavoriteList(filteredList)
            // 隐藏外部的空状态提示（因为卡片内部会处理空状态）
            vb.emptyTitle.isVisible = false
        }
    }

    private fun initVersion() {
        try {
            val packageInfo = requireContext().packageManager.getPackageInfo(
                requireContext().packageName,
                0
            )
            val versionName = packageInfo.versionName ?: "1.0"
            vb.tvVersion.text = versionName
        } catch (e: PackageManager.NameNotFoundException) {
            vb.tvVersion.text = "1.0"
        } catch (e: Exception) {
            vb.tvVersion.text = "1.0"
        }
    }

    private fun initAbout() {
        vb.layoutAbout.setOnClickListener {
            // TODO: 可以打开关于对话框或关于页面
        }
    }
}
