package com.apps.pixwall.view

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.apps.pixwall.IApplication
import com.apps.pixwall.adapter.MainOutAdapter
import com.apps.pixwall.data.MainViewModel
import com.apps.pixwall.data.Paper
import com.apps.pixwall.databinding.FragmentCategoryBinding
import com.apps.pixwall.listener.MainItemListener
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch

class CategoryFragment : Fragment(),MainItemListener {
    private lateinit var binding:FragmentCategoryBinding
    private lateinit var viewModel:MainViewModel
    private lateinit var adapter: MainOutAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding=FragmentCategoryBinding.inflate(inflater,container,false)
        init()
        return binding.root
    }
    private fun init(){
        viewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        adapter=MainOutAdapter()
        adapter.setListener(this)
        binding.rvView.adapter = adapter
        binding.rvView.layoutManager = LinearLayoutManager(requireContext())
        viewModel.coverMap.value?.takeIf { it.isNotEmpty() }?.let {
            Log.d("DataLoad", "hasLoad")
            updateAdapter()
        }

        viewModel.loadAllCategoryCovers()

        viewModel.loadingState.observe(viewLifecycleOwner) { isLoading ->
            viewModel.coverMap.value?.let { coverMap ->
                if (!isLoading && coverMap.isNotEmpty()) {
                    updateAdapter()
                }
            }
        }

        viewModel.coverMap.observe(viewLifecycleOwner) { coverMap ->
            viewModel.loadingState.value?.let { isLoading ->
                if (!isLoading && coverMap.isNotEmpty()) {
                    updateAdapter()
                }
            }
        }
    }
    private fun updateAdapter() {
        val categoryList = IApplication.categoryList
        val coverMap = viewModel.coverMap.value

        // 确保数据一致性
        val coversForCategories = categoryList.map { categoryName ->
            coverMap?.get(categoryName) ?: emptyList()
        }

        adapter.setList(categoryList, coversForCategories)
        adapter.notifyDataSetChanged()
        Log.d("AdapterUpdate", "refresh data")
        categoryList.forEachIndexed { index, category ->
            val count = coversForCategories[index].size
            Log.d("DataDebug", "[$index] $category: $count data")
        }
    }

    override fun more(name: String) {
        val intent=Intent(requireActivity(),MorePaperActivity::class.java)
        intent.putExtra(MorePaperActivity.titleName,name)
        startActivity(intent)
    }
}