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

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.audio_content.series.detail.SeriesDetailActivity
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.DifferentSpacingItemDecoration
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivitySeriesListAllBinding
import org.koin.android.ext.android.inject
import kotlin.math.roundToInt

class SeriesListAllActivity : BaseActivity<ActivitySeriesListAllBinding>(
    ActivitySeriesListAllBinding::inflate
) {

    private val viewModel: SeriesListAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var seriesAdapter: SeriesListAdapter

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

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

        bindData()

        viewModel.creatorId = creatorId
        viewModel.getSeriesList()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "시리즈 전체보기"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        seriesAdapter = SeriesListAdapter(
            itemWidth = ((screenWidth - (13.3 * 3)) / 3).roundToInt(),
            onClickItem = {
                startActivity(
                    Intent(applicationContext, SeriesDetailActivity::class.java).apply {
                        putExtra(Constants.EXTRA_SERIES_ID, it)
                    }
                )
            },
            onClickCreator = {},
            isVisibleCreator = false
        )

        val spanCount = 3
        val horizontalSpacing = 20
        val verticalSpacing = 100
        val recyclerView = binding.rvSeriesAll
        recyclerView.layoutManager = GridLayoutManager(this, spanCount)

        recyclerView.addItemDecoration(
            DifferentSpacingItemDecoration(
                spanCount = spanCount,
                horizontalSpacing = horizontalSpacing,
                verticalSpacing = verticalSpacing,
                includeEdge = true

            )
        )

        recyclerView.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.getSeriesList()
                }
            }
        })

        recyclerView.adapter = seriesAdapter
    }

    private 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.seriesListLiveData.observe(this) {
            if (viewModel.page - 1 == 1) {
                seriesAdapter.clear()
                binding.rvSeriesAll.scrollToPosition(0)
            }

            seriesAdapter.addItems(it)
        }
    }
}
