package kr.co.vividnext.sodalive.live.room.like

import android.annotation.SuppressLint
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import kr.co.vividnext.sodalive.databinding.DialogLiveRoomHeartRankingBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat

@SuppressLint("NotifyDataSetChanged")
class LiveRoomHeartRankingDialog(
    private val activity: FragmentActivity,
    layoutInflater: LayoutInflater,
    getHeartRanking: ((GetLiveRoomHeartListResponse) -> Unit) -> Unit
) {
    private val bottomSheetDialog: BottomSheetDialog = BottomSheetDialog(activity)
    private val dialogView = DialogLiveRoomHeartRankingBinding.inflate(layoutInflater)
    private val adapter = LiveRoomHeartRankingAdapter()

    init {
        bottomSheetDialog.setContentView(dialogView.root)
        bottomSheetDialog.setCancelable(false)

        dialogView.ivClose.setOnClickListener { bottomSheetDialog.dismiss() }
        setupRecyclerView()

        getHeartRanking {
            adapter.items.clear()
            adapter.items.addAll(it.heartList)
            adapter.notifyDataSetChanged()
            dialogView.tvTotalHeart.text = it.totalHeart.moneyFormat()
            dialogView.tvTotalCount.text = it.totalCount.moneyFormat()
        }
    }

    private fun setupRecyclerView() {
        dialogView.rvHeartRanking.layoutManager = LinearLayoutManager(
            activity,
            LinearLayoutManager.VERTICAL,
            false
        )

        dialogView.rvHeartRanking.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, 1, 2 -> {
                        outRect.top = 0
                        outRect.bottom = 0
                    }

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

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

        dialogView.rvHeartRanking.adapter = adapter
    }

    fun show() {
        bottomSheetDialog.show()
    }
}
