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

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.AudioContentViewModel
import kr.co.vividnext.sodalive.audio_content.all.AudioContentNewAllAdapter
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
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.ActivityAudioContentAllByThemeBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentAllByThemeActivity : BaseActivity<ActivityAudioContentAllByThemeBinding>(
    ActivityAudioContentAllByThemeBinding::inflate
) {
    private val viewModel: AudioContentAllByThemeViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AudioContentNewAllAdapter

    private var themeId: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        themeId = intent.getLongExtra(Constants.EXTRA_THEME_ID, 0)

        if (themeId <= 0) {
            Toast.makeText(
                applicationContext,
                "잘못된 요청입니다.\n다시 시도해 주세요.",
                Toast.LENGTH_LONG
            ).show()

            finish()
        }

        super.onCreate(savedInstanceState)

        bindData()
        viewModel.getContentList(themeId = themeId)
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.setOnClickListener { finish() }

        val spanCount = 3
        val spacing = 40
        adapter = 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.rvContentAll.layoutManager = GridLayoutManager(this, spanCount)
        binding.rvContentAll.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, true))

        binding.rvContentAll.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.getContentList(themeId = themeId)
                }
            }
        })

        binding.rvContentAll.adapter = adapter

        binding.tvSortNewest.setOnClickListener {
            viewModel.changeSort(AudioContentViewModel.Sort.NEWEST)
        }

        binding.tvSortPriceLow.setOnClickListener {
            viewModel.changeSort(AudioContentViewModel.Sort.PRICE_LOW)
        }

        binding.tvSortPriceHigh.setOnClickListener {
            viewModel.changeSort(AudioContentViewModel.Sort.PRICE_HIGH)
        }
    }

    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.contentListLiveData.observe(this) {
            if (viewModel.page - 1 == 1) {
                adapter.clear()
                binding.rvContentAll.scrollToPosition(0)
            }

            binding.tvTotalCount.text = "${it.totalCount}"
            binding.toolbar.tvBack.text = it.theme
            adapter.addItems(it.items)
        }

        viewModel.sort.observe(this) {
            deselectSort()
            selectSort(
                when (it) {
                    AudioContentViewModel.Sort.PRICE_HIGH -> {
                        binding.tvSortPriceHigh
                    }

                    AudioContentViewModel.Sort.PRICE_LOW -> {
                        binding.tvSortPriceLow
                    }

                    else -> {
                        binding.tvSortNewest
                    }
                }
            )

            viewModel.getContentList(themeId = themeId)
        }
    }

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

        binding.tvSortNewest.setTextColor(color)
        binding.tvSortPriceLow.setTextColor(color)
        binding.tvSortPriceHigh.setTextColor(color)
    }

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