package kr.co.vividnext.sodalive.audio_content.series.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.audio_content.series.content.SeriesContentAdapter
import kr.co.vividnext.sodalive.audio_content.series.content.SeriesContentAllActivity
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.databinding.FragmentSeriesDetailHomeBinding

class SeriesDetailHomeFragment : BaseFragment<FragmentSeriesDetailHomeBinding>(
    FragmentSeriesDetailHomeBinding::inflate
) {
    private var seriesDetailResponse: GetSeriesDetailResponse? = null

    private lateinit var adapter: SeriesContentAdapter

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

        if (arguments != null) {
            seriesDetailResponse = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                requireArguments().getParcelable(
                    Constants.EXTRA_SERIES,
                    GetSeriesDetailResponse::class.java
                )
            } else {
                requireArguments().getParcelable(Constants.EXTRA_SERIES)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (seriesDetailResponse != null) {
            setContent()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setContent() {
        binding.tvTotalCount.text = "(${seriesDetailResponse!!.contentCount})"
        binding.llContentAll.setOnClickListener {
            startActivity(
                Intent(requireActivity(), SeriesContentAllActivity::class.java).apply {
                    putExtra(Constants.EXTRA_SERIES_ID, seriesDetailResponse!!.seriesId)
                    putExtra(Constants.EXTRA_SERIES_TITLE, seriesDetailResponse!!.title)
                }
            )
        }

        adapter = SeriesContentAdapter {
            startActivity(
                Intent(requireActivity(), AudioContentDetailActivity::class.java).apply {
                    putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it)
                }
            )
        }

        binding.rvContent.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.VERTICAL,
            false
        )

        binding.rvContent.addItemDecoration(
            DividerItemDecoration(
                requireContext(),
                DividerItemDecoration.VERTICAL
            )
        )

        binding.rvContent.adapter = adapter
        adapter.addItems(seriesDetailResponse!!.contentList)
    }
}
