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.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.adapter.HighlightNewsAdapter
import com.sambath.kunkhmer.adapter.TopNewsAdapter
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.remote.Highlight
import com.sambath.kunkhmer.remote.HighlightData
import com.sambath.kunkhmer.remote.News
import com.sambath.kunkhmer.remote.NewsData
import com.sambath.kunkhmer.screen.lives.LiveDetailFragment
import kotlinx.android.synthetic.main.fragment_news.view.recyclerViewNews
import kotlinx.android.synthetic.main.fragment_news.view.recyclerViewNewsHeader
import kotlinx.android.synthetic.main.fragment_news.view.selectedTabTextView
import kotlinx.android.synthetic.main.fragment_news.view.tabLayout

class NewsFragment : Fragment(), TopNewsAdapter.OnItemClickListener, HighlightNewsAdapter.OnItemClickListener {
    private var _root: View? = null
    private val binding get() = _root!!
    private lateinit var newsViewModel: NewsViewModel
    private lateinit var topNewsAdapter: TopNewsAdapter
    private lateinit var highlightNewsAdapter: HighlightNewsAdapter
    private var cardList: List<Highlight>? = null

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

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _root = inflater.inflate(R.layout.fragment_news, container, false)

        topNewsAdapter = TopNewsAdapter(mutableListOf(), this)
        highlightNewsAdapter = HighlightNewsAdapter(mutableListOf(), this)

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

        newsViewModel = NewsViewModel(App.injectApiService(), App.injectPrefHelper())
        newsViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })

        setTab()

        return binding
    }

    private fun render(state: NewsViewState) {
        if (state.isLoginSuccess) {
            if(state.newsData != null) {
                updateNewsFeed(state.newsData)
            }

            if(state.highlightData != null) {
                updateHighlight(state.highlightData)
                cardList = state.highlightData.obj
            }
        }
        // Other state handling...
    }

    private fun updateNewsFeed(newsData: NewsData) {
        topNewsAdapter.cardList = newsData.obj
        topNewsAdapter.notifyDataSetChanged()
    }

    private fun updateHighlight(highlightData: HighlightData) {
        highlightNewsAdapter.cardList = highlightData.obj
        highlightNewsAdapter.notifyDataSetChanged()
    }

    private fun setTab() {
        val tabTitles = listOf("TOP NEWS", "HIGHLIGHT")

        // Populate TabLayout with dynamic tabs
        for (title in tabTitles) {
            val tab = binding.tabLayout.newTab().setText(title)
            binding.tabLayout.addTab(tab)
        }

        // Set tab click listener
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    val selectedTitle = it.text.toString()
                    binding.selectedTabTextView.text = "Selected Tab: $selectedTitle"
                    when (it.position) {
                        0 -> {
                            //Top News
                            binding.recyclerViewNews.apply {
                                layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                                adapter = topNewsAdapter
                            }
                            fetchTopNewsAndUpdateAdapter()
                        }
                        1 -> {
                            binding.recyclerViewNews.apply {
                                layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                                adapter = highlightNewsAdapter
                            }
                            // Highlight
                            fetchHighlightNewsAndUpdateAdapter()
                        }
                        // Add more cases if needed
                    }
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                // No action needed
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                // No action needed
            }
        })

        //setNewsHeaderFeed()
        fetchTopNewsAndUpdateAdapter()
    }

    private fun fetchTopNewsAndUpdateAdapter() {
        // Fetch top news from ViewModel
        newsViewModel.getNews()
    }

    private fun fetchHighlightNewsAndUpdateAdapter() {
        // Fetch highlight news from ViewModel
        newsViewModel.getHighlight()
    }

    private fun removeNewsHeaderFeed() {
        val recyclerView = binding.recyclerViewNewsHeader
        recyclerView.adapter = null
    }

    interface TabSelectionListener {
        fun onTabSelected(tabIndex: Int)
    }

    fun selectTab(tabIndex: Int) {
        binding.tabLayout.getTabAt(tabIndex)?.select()
    }

    override fun onItemClick(newsItem: News) {
        val topNewsDetailFragment = TopNewsDetailFragment()
        val bundle = Bundle()
        bundle.putString("news_id", newsItem.id)
        topNewsDetailFragment.arguments = bundle

        parentFragmentManager.beginTransaction()
            .replace(R.id.nav_host_fragment_activity_main, topNewsDetailFragment)
            .addToBackStack("NewsFragment") // Add to back stack to handle the back navigation
            .commit()
    }

    override fun onItemClick(position: Int) {
        val clickedItem = cardList!![position]
        val liveDetailFragment = LiveDetailFragment()

        // You can pass data to the LiveDetailFragment using arguments if needed
        val bundle = Bundle()
        bundle.putString("image_url", "")
        bundle.putString("title", clickedItem.title)
        bundle.putString("description", clickedItem.title)
        bundle.putString("url", clickedItem.url)
        liveDetailFragment.arguments = bundle

        // Replace the current fragment with the LiveDetailFragment
        parentFragmentManager.beginTransaction()
            .replace(R.id.nav_host_fragment_activity_main, liveDetailFragment)
            .addToBackStack(null) // Add to back stack to handle the back navigation
            .commit()
    }
}