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

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
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.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.GridSpacingItemDecoration
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityAudioContentNewAllBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentNewAllActivity : BaseActivity<ActivityAudioContentNewAllBinding>(
    ActivityAudioContentNewAllBinding::inflate
) {
    private val viewModel: AudioContentNewAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    private lateinit var newContentThemeAdapter: AudioContentMainNewContentThemeAdapter
    private lateinit var newContentAdapter: AudioContentNewAllAdapter

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

        bindData()
        viewModel.getThemeList()
        viewModel.getNewContentList()
    }

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

        setupNewContentTheme()
        setupNewContent()
    }

    private fun setupNewContentTheme() {
        newContentThemeAdapter = AudioContentMainNewContentThemeAdapter {
            newContentAdapter.clear()
            viewModel.selectTheme(it)
        }

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

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

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

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

        binding.rvNewContentTheme.adapter = newContentThemeAdapter
    }

    private fun setupNewContent() {
        val spanCount = 3
        val spacing = 40
        newContentAdapter = AudioContentNewAllAdapter(
            itemWidth = (screenWidth - (spacing * (spanCount + 1))) / 3,
            onClickItem = {
                startActivity(
                    Intent(this, AudioContentDetailActivity::class.java).apply {
                        putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it)
                    }
                )
            },
            onClickCreator = {
                startActivity(
                    Intent(this, UserProfileActivity::class.java).apply {
                        putExtra(Constants.EXTRA_USER_ID, it)
                    }
                )
            }
        )

        binding.rvContent.layoutManager = GridLayoutManager(this, spanCount)
        binding.rvContent.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, true))

        binding.rvContent.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.getNewContentList()
                }
            }
        })

        binding.rvContent.adapter = newContentAdapter
    }

    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.themeListLiveData.observe(this) {
            newContentThemeAdapter.addItems(it)
        }

        viewModel.newContentListLiveData.observe(this) {
            newContentAdapter.addItems(it)
        }

        viewModel.newContentTotalCountLiveData.observe(this) {
            binding.tvTotalCount.text = "$it"
        }
    }
}
