package kr.co.vividnext.sodalive.mypage.alarm.select_audio_content

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.order.AudioContentOrderListViewModel
import kr.co.vividnext.sodalive.audio_content.order.OrderType
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.ActivityAlarmSelectAudioContentBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AlarmSelectAudioContentActivity : BaseActivity<ActivityAlarmSelectAudioContentBinding>(
    ActivityAlarmSelectAudioContentBinding::inflate
) {
    private val viewModel: AudioContentOrderListViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AlarmSelectAudioContentAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        bindData()
        viewModel.getAudioContentOrderList { finish() }
    }

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

        adapter = AlarmSelectAudioContentAdapter {
            val resultIntent = Intent().apply {
                putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it.contentId)
                putExtra(Constants.EXTRA_AUDIO_CONTENT_TITLE, it.title)
                putExtra(Constants.EXTRA_AUDIO_CONTENT_CREATOR_NICKNAME, it.creatorNickname)
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }

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

        binding.rvOrderList.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 = 13.3f.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }

                    adapter.itemCount - 1 -> {
                        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.rvOrderList.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.getAudioContentOrderList {}
                }
            }
        })

        binding.rvOrderList.adapter = adapter
    }

    @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.orderList.observe(this) { items ->
            val keepItems = items.filter { it.orderType == OrderType.KEEP }

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

            adapter.items.addAll(keepItems)
            adapter.notifyDataSetChanged()

            if (adapter.items.count() + keepItems.size > 0) {
                binding.rvOrderList.visibility = View.VISIBLE
                binding.tvEmptyOrderList.visibility = View.GONE
            } else {
                binding.rvOrderList.visibility = View.GONE
                binding.tvEmptyOrderList.visibility = View.VISIBLE
            }
        }
    }
}
