package kr.co.vividnext.sodalive.audio_content.all

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.audio_content.main.new_content.AudioContentMainNewContentThemeAdapter
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.ActivityAudioContentRankingAllBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentRankingAllActivity : BaseActivity<ActivityAudioContentRankingAllBinding>(
    ActivityAudioContentRankingAllBinding::inflate
) {
    private val viewModel: AudioContentRankingAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AudioContentRankingAllAdapter
    private lateinit var sortAdapter: AudioContentMainNewContentThemeAdapter

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

        bindData()
        viewModel.getAudioContentRankingSortType()
        viewModel.getAudioContentRanking()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.setOnClickListener { finish() }
        binding.toolbar.tvBack.text = "인기 콘텐츠"

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

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

        binding.rvContentRanking.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)

                outRect.left = 13.3f.dpToPx().toInt()
                outRect.right = 13.3f.dpToPx().toInt()

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.top = 0
                        outRect.bottom = 10f.dpToPx().toInt()
                    }

                    adapter.itemCount - 1 -> {
                        outRect.top = 10f.dpToPx().toInt()
                        outRect.bottom = 0
                    }

                    else -> {
                        outRect.top = 10f.dpToPx().toInt()
                        outRect.bottom = 10f.dpToPx().toInt()
                    }
                }
            }
        })

        binding.rvContentRanking.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.getAudioContentRanking()
                }
            }
        })

        binding.rvContentRanking.adapter = adapter

        setupContentRankingSortType()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupContentRankingSortType() {
        sortAdapter = AudioContentMainNewContentThemeAdapter {
            adapter.items.clear()
            adapter.notifyDataSetChanged()
            viewModel.selectSort(sort = it)
        }

        binding.rvContentRankingSort.layoutManager = LinearLayoutManager(
            this,
            LinearLayoutManager.HORIZONTAL,
            false
        )

        binding.rvContentRankingSort.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.left = 0
                        outRect.right = 4f.dpToPx().toInt()
                    }

                    sortAdapter.itemCount - 1 -> {
                        outRect.left = 4f.dpToPx().toInt()
                        outRect.right = 0
                    }

                    else -> {
                        outRect.left = 4f.dpToPx().toInt()
                        outRect.right = 4f.dpToPx().toInt()
                    }
                }
            }
        })

        binding.rvContentRankingSort.adapter = sortAdapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

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

        viewModel.dateStringLiveData.observe(this) {
            binding.tvDate.text = it
        }

        viewModel.contentRankingItemsLiveData.observe(this) {
            if (viewModel.page == 2) {
                adapter.items.clear()
            }

            adapter.items.addAll(it)
            adapter.notifyDataSetChanged()
        }

        viewModel.contentRankingSortListLiveData.observe(this) {
            sortAdapter.addItems(it)
        }
    }
}
