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

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.audio_content.series.SeriesListAllViewModel
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivitySeriesContentAllBinding
import org.koin.android.ext.android.inject

class SeriesContentAllActivity : BaseActivity<ActivitySeriesContentAllBinding>(
    ActivitySeriesContentAllBinding::inflate
) {
    private val viewModel: SeriesContentAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: SeriesContentAdapter

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

        val seriesId = intent.getLongExtra(Constants.EXTRA_SERIES_ID, 0)
        if (seriesId <= 0) {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }

        bindData()

        viewModel.seriesId = seriesId
        viewModel.getSeriesContentList()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)

        val seriesTitle = intent.getStringExtra(Constants.EXTRA_SERIES_TITLE) ?: ""
        binding.toolbar.tvBack.text = if (seriesTitle.isNotBlank()) {
            "$seriesTitle - 전체회차 듣기"
        } else {
            " 전체회차 듣기"
        }
        binding.toolbar.tvBack.setOnClickListener { finish() }

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

        binding.rvSeriesContentAll.layoutManager = LinearLayoutManager(
            applicationContext,
            LinearLayoutManager.VERTICAL,
            false
        )

        binding.rvSeriesContentAll.addItemDecoration(
            DividerItemDecoration(
                applicationContext,
                DividerItemDecoration.VERTICAL
            )
        )

        binding.rvSeriesContentAll.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val lastVisibleItemPosition = (recyclerView.layoutManager as LinearLayoutManager?)!!
                    .findLastCompletelyVisibleItemPosition()
                val itemTotalCount = recyclerView.adapter!!.itemCount - 1

                // 스크롤이 끝에 도달했는지 확인
                if (!recyclerView.canScrollVertically(1) &&
                    lastVisibleItemPosition == itemTotalCount
                ) {
                    viewModel.getSeriesContentList()
                }
            }
        })

        binding.rvSeriesContentAll.adapter = adapter

        binding.tvSortNewest.setOnClickListener {
            viewModel.changeSort(SeriesListAllViewModel.SeriesSortType.NEWEST)
        }

        binding.tvSortOldest.setOnClickListener {
            viewModel.changeSort(SeriesListAllViewModel.SeriesSortType.OLDEST)
        }
    }

    fun bindData() {
        viewModel.toastLiveData.observe(this) {
            it?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show() }
        }

        viewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth, "")
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.seriesContentListLiveData.observe(this) {
            adapter.addItems(it)
        }

        viewModel.sortLiveData.observe(this) {
            deselectSort()
            selectSort(
                when (it) {
                    SeriesListAllViewModel.SeriesSortType.OLDEST -> {
                        binding.tvSortOldest
                    }

                    else -> {
                        binding.tvSortNewest
                    }
                }
            )
        }
    }

    private fun deselectSort() {
        val color = ContextCompat.getColor(
            applicationContext,
            R.color.color_88e2e2e2
        )

        binding.tvSortNewest.setTextColor(color)
        binding.tvSortOldest.setTextColor(color)
    }

    private fun selectSort(view: TextView) {
        view.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_e2e2e2
            )
        )

        adapter.clear()
        viewModel.getSeriesContentList()
    }
}
