package kr.co.vividnext.sodalive.audio_content.curation

import android.annotation.SuppressLint
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.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityAudioContentCurationBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentCurationActivity : BaseActivity<ActivityAudioContentCurationBinding>(
    ActivityAudioContentCurationBinding::inflate
) {

    private val viewModel: AudioContentCurationViewModel by inject()

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

    private var curationId: Long = 0
    private lateinit var title: String

    override fun onCreate(savedInstanceState: Bundle?) {
        title = intent.getStringExtra(Constants.EXTRA_AUDIO_CONTENT_CURATION_TITLE) ?: ""
        curationId = intent.getLongExtra(Constants.EXTRA_AUDIO_CONTENT_CURATION_ID, 0)
        super.onCreate(savedInstanceState)

        if (title.isBlank() || curationId <= 0) {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }

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

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

        adapter = AudioContentNewAllAdapter(
            itemWidth = (screenWidth - 40f.dpToPx().toInt()) / 2,
            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.rvCuration.layoutManager = GridLayoutManager(this, 2)

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

                val position = parent.getChildAdapterPosition(view)
                if (position % 2 == 0) {
                    outRect.left = 13.3f.dpToPx().toInt()
                    outRect.right = 6.7f.dpToPx().toInt()
                } else {
                    outRect.left = 6.7f.dpToPx().toInt()
                    outRect.right = 13.3f.dpToPx().toInt()
                }

                when (position) {
                    0, 1 -> {
                        outRect.top = 13.3f.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }

                    adapter.itemCount - 1, adapter.itemCount - 2 -> {
                        outRect.top = 6.7f.dpToPx().toInt()
                        outRect.bottom = 13.3f.dpToPx().toInt()
                    }

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

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

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

    @SuppressLint("NotifyDataSetChanged")
    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.rvCuration.scrollToPosition(0)
            }

            binding.tvTotalCount.text = "${it.totalCount}"
            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(curationId = curationId)
        }
    }

    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
            )
        )
    }
}
