package kr.co.vividnext.sodalive.explorer.profile.donation

import android.annotation.SuppressLint
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.R
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.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivityUserProfileLiveAllBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat
import org.koin.android.ext.android.inject

class UserProfileDonationAllViewActivity : BaseActivity<ActivityUserProfileLiveAllBinding>(
    ActivityUserProfileLiveAllBinding::inflate
) {

    private val viewModel: UserProfileDonationAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: UserProfileDonationAllAdapter

    private var userId: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        userId = intent.getLongExtra(Constants.EXTRA_USER_ID, 0)
        super.onCreate(savedInstanceState)

        if (userId > 0) {
            bindData()

            viewModel.getCreatorProfileDonationRanking(userId)
        } else {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "후원랭킹 전체보기"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        setupDonationRankingView()
    }

    private fun setupDonationRankingView() {
        val recyclerView = binding.rvLiveAll
        adapter = UserProfileDonationAllAdapter(userId = userId)

        recyclerView.layoutManager = LinearLayoutManager(
            applicationContext,
            LinearLayoutManager.VERTICAL,
            false
        )

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

                outRect.left = 20.dpToPx().toInt()
                outRect.right = 20.dpToPx().toInt()

                when (parent.getChildAdapterPosition(view)) {
                    0, 1, 2 -> {
                        outRect.top = 0
                        outRect.bottom = 0
                        outRect.left = 13.3f.dpToPx().toInt()
                        outRect.right = 13.3f.dpToPx().toInt()
                    }

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

        recyclerView.adapter = adapter

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val lastVisiblePosition = (recyclerView.layoutManager as LinearLayoutManager)
                    .findLastVisibleItemPosition()
                val itemTotalCount = adapter.itemCount - 1

                if (itemTotalCount > 0 && lastVisiblePosition == itemTotalCount) {
                    viewModel.getCreatorProfileDonationRanking(userId)
                }
            }
        })

        binding.swipeRefreshLayout.setOnRefreshListener {
            adapter.items.clear()
            viewModel.refresh(userId)

            binding.swipeRefreshLayout.isRefreshing = false
        }

        if (SharedPreferenceManager.userId == userId) {
            binding.llTotal.visibility = View.VISIBLE
            binding.llVisibleDonationRanking.visibility = View.VISIBLE
            binding.ivVisibleDonationRank.setOnClickListener {
                viewModel.onClickToggleVisibleDonationRank()
            }
        } else {
            binding.llTotal.visibility = View.GONE
            binding.llVisibleDonationRanking.visibility = View.GONE
        }
    }

    @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.donationLiveData.observe(this) {
            binding.tvCanToday.text = it.accumulatedCansToday.moneyFormat()
            binding.tvCanLastWeek.text = it.accumulatedCansLastWeek.moneyFormat()
            binding.tvCanThisMonth.text = it.accumulatedCansThisMonth.moneyFormat()

            binding.tvTotalCount.text = "${it.totalCount}"
            adapter.items.addAll(it.userDonationRanking)
            adapter.notifyDataSetChanged()
        }

        viewModel.isVisibleDonationRank.observe(this) {
            binding.ivVisibleDonationRank.setImageResource(
                if (it) {
                    R.drawable.btn_toggle_on_big
                } else {
                    R.drawable.btn_toggle_off_big
                }
            )
        }
    }
}
