package com.sambath.kunkhmer.screen.news

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.adapter.TopNewsDetailAdapter
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.remote.News
import com.sambath.kunkhmer.remote.NewsDetail
import kotlinx.android.synthetic.main.fragment_top_news_detail.view.back_iv
import kotlinx.android.synthetic.main.fragment_top_news_detail.view.recyclerViewTopNewDetail

class TopNewsDetailFragment : Fragment() {
    private var _root: View? = null
    private val binding get() = _root!!
    private var newsItem: News? = null
    private lateinit var newsDetailViewModel: NewsDetailViewModel
    private lateinit var topNewsDetailAdapter: TopNewsDetailAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _root = inflater.inflate(R.layout.fragment_top_news_detail, container, false)
        val newsId = arguments?.getString("news_id")

        topNewsDetailAdapter = TopNewsDetailAdapter(NewsDetail())

        // Set adapters
        binding.recyclerViewTopNewDetail.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = topNewsDetailAdapter
        }

        newsDetailViewModel = NewsDetailViewModel(App.injectApiService(), App.injectPrefHelper())
        newsDetailViewModel.getNewsDetail(newsId!!)
        newsDetailViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })

        binding.back_iv.setOnClickListener{
            val newsFragmentId = R.id.newsFragment
            findNavController().popBackStack()
        }

        binding.back_iv.setOnClickListener {
            requireActivity().supportFragmentManager.popBackStack()
        }

        return _root
    }

    private fun render(state: NewsDetailViewState) {
        if (state.isLoginSuccess) {
            if(state.newsDetailData != null) {
                updateNewsDetailFeed(state.newsDetailData)
            }
        }
        // Other state handling...
    }

    private fun updateNewsDetailFeed(newsDetailData: NewsDetail) {
        topNewsDetailAdapter.newsDetail = newsDetailData
        topNewsDetailAdapter.notifyDataSetChanged()
    }
}