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

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.webkit.URLUtil
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.CircleCropTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.AudioContentActivity
import kr.co.vividnext.sodalive.audio_content.AudioContentAdapter
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.audio_content.upload.AudioContentUploadActivity
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.ActivityUserProfileBinding
import kr.co.vividnext.sodalive.explorer.profile.cheers.UserProfileCheersAdapter
import kr.co.vividnext.sodalive.explorer.profile.donation.UserProfileDonationAdapter
import kr.co.vividnext.sodalive.explorer.profile.donation.UserProfileDonationAllViewActivity
import kr.co.vividnext.sodalive.explorer.profile.fantalk.UserProfileFantalkAllViewActivity
import kr.co.vividnext.sodalive.explorer.profile.follow.UserFollowerListActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat
import kr.co.vividnext.sodalive.live.LiveViewModel
import kr.co.vividnext.sodalive.live.reservation.complete.LiveReservationCompleteActivity
import kr.co.vividnext.sodalive.live.room.LiveRoomActivity
import kr.co.vividnext.sodalive.live.room.dialog.LivePaymentDialog
import kr.co.vividnext.sodalive.live.room.dialog.LiveRoomPasswordDialog
import kr.co.vividnext.sodalive.report.CheersReportDialog
import kr.co.vividnext.sodalive.report.ProfileReportDialog
import kr.co.vividnext.sodalive.report.ReportType
import kr.co.vividnext.sodalive.report.UserReportDialog
import org.koin.android.ext.android.inject

class UserProfileActivity : BaseActivity<ActivityUserProfileBinding>(
    ActivityUserProfileBinding::inflate
) {

    private val viewModel: UserProfileViewModel by inject()
    private val liveViewModel: LiveViewModel by inject()

    private lateinit var imm: InputMethodManager
    private lateinit var loadingDialog: LoadingDialog
    private lateinit var liveAdapter: UserProfileLiveAdapter
    private lateinit var audioContentAdapter: AudioContentAdapter
    private lateinit var donationAdapter: UserProfileDonationAdapter
    private lateinit var similarCreatorAdapter: UserProfileSimilarCreatorAdapter
    private lateinit var cheersAdapter: UserProfileCheersAdapter

    private lateinit var noticeWriteLauncher: ActivityResultLauncher<Intent>

    private val handler = Handler(Looper.getMainLooper())
    private var userId: Long = 0

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

        imm = getSystemService(Service.INPUT_METHOD_SERVICE) as InputMethodManager
        noticeWriteLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                val writtenNotice = it.data?.getStringExtra("notice")
                binding.tvNotice.text = writtenNotice?.ifBlank {
                    "공지사항이 없습니다."
                }
            }
        }

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

    override fun onResume() {
        super.onResume()
        viewModel.getCreatorProfile(userId) { finish() }
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.tvBack.text = "채널"
        binding.tvBack.setOnClickListener { finish() }
        binding.ivMenu.setOnClickListener {
            showOptionMenu(
                this,
                binding.ivMenu,
            )
        }
        binding.layoutUserProfile.ivShare.setOnClickListener {
            viewModel.shareChannel(userId = userId) {
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "text/plain"
                intent.putExtra(Intent.EXTRA_TEXT, it)

                val shareIntent = Intent.createChooser(intent, "채널 공유")
                startActivity(shareIntent)
            }
        }

        setupLiveView()
        setupDonationView()
        setupSimilarCreatorView()
        setupFanTalkView()
        setupAudioContentListView()
    }

    private fun hideKeyboard(onAfterExecute: () -> Unit) {
        handler.postDelayed({
            imm.hideSoftInputFromWindow(
                window.decorView.applicationWindowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
            onAfterExecute()
        }, 100)
    }

    private fun showOptionMenu(context: Context, v: View) {
        val popup = PopupMenu(context, v)
        val inflater = popup.menuInflater

        if (viewModel.creatorProfileLiveData.value!!.isBlock) {
            inflater.inflate(R.menu.user_profile_option_menu_2, popup.menu)

            popup.setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.menu_user_block -> {
                        viewModel.userUnBlock(userId)
                    }

                    R.id.menu_user_report -> {
                        showUserReportDialog()
                    }

                    R.id.menu_profile_report -> {
                        showProfileReportDialog()
                    }
                }

                true
            }
        } else {
            inflater.inflate(R.menu.user_profile_option_menu, popup.menu)

            popup.setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.menu_user_block -> {
                        showUserBlockDialog()
                    }

                    R.id.menu_user_report -> {
                        showUserReportDialog()
                    }

                    R.id.menu_profile_report -> {
                        showProfileReportDialog()
                    }
                }

                true
            }
        }

        popup.show()
    }

    private fun showUserBlockDialog() {
        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("사용자 차단")
        dialog.setMessage(
            "${binding.layoutUserProfile.tvNickname.text}님을 차단하시겠습니까?\n\n" +
                "사용자를 차단하면 사용자는 아래 기능이 제한됩니다.\n" +
                "- 내가 개설한 라이브 입장 불가\n" +
                "- 나에게 메시지 보내기 불가\n" +
                "- 내 채널의 팬Talk 작성불가"
        )
        dialog.setPositiveButton("차단") { _, _ ->
            viewModel.userBlock(userId)
        }
        dialog.setNegativeButton("취소") { _, _ -> }
        dialog.show()
    }

    private fun showUserReportDialog() {
        val dialog = UserReportDialog(this, layoutInflater) {
            viewModel.report(
                type = ReportType.USER,
                userId = userId,
                reason = it
            )
        }

        dialog.show(screenWidth)
    }

    private fun showProfileReportDialog() {
        val dialog = ProfileReportDialog(this, layoutInflater) {
            viewModel.report(
                type = ReportType.PROFILE,
                userId = userId
            )
        }

        dialog.show(screenWidth)
    }

    private fun setupLiveView() {
        val recyclerView = binding.layoutUserProfileLive.rvLive
        liveAdapter = UserProfileLiveAdapter(
            onClickParticipant = { enterLiveRoom(roomId = it.roomId) },
            onClickReservation = { reservationRoom(roomId = it.roomId) }
        )

        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)

                when (parent.getChildAdapterPosition(view)) {
                    liveAdapter.itemCount - 1 -> {
                        outRect.bottom = 0
                    }

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

        recyclerView.adapter = liveAdapter
    }

    private fun setupDonationView() {
        binding.layoutUserProfileDonation.tvAll.setOnClickListener {
            val intent = Intent(applicationContext, UserProfileDonationAllViewActivity::class.java)
            intent.putExtra(Constants.EXTRA_USER_ID, userId)
            startActivity(intent)
        }

        val recyclerView = binding.layoutUserProfileDonation.rvDonation
        donationAdapter = UserProfileDonationAdapter()

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

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

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.left = 0
                        outRect.right = 6.7f.dpToPx().toInt()
                    }

                    donationAdapter.itemCount - 1 -> {
                        outRect.left = 6.7f.dpToPx().toInt()
                        outRect.right = 0
                    }

                    else -> {
                        outRect.left = 6.7f.dpToPx().toInt()
                        outRect.right = 6.7f.dpToPx().toInt()
                    }
                }
            }
        })

        recyclerView.adapter = donationAdapter
    }

    private fun setupSimilarCreatorView() {
        val recyclerView = binding.layoutUserProfileSimilarCreator.rvSimilarCreator
        similarCreatorAdapter = UserProfileSimilarCreatorAdapter {
            val intent = Intent(applicationContext, UserProfileActivity::class.java)
            intent.putExtra(Constants.EXTRA_USER_ID, it.userId)
            startActivity(intent)
        }

        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)

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.top = 0
                        outRect.bottom = 10f.dpToPx().toInt()
                    }

                    similarCreatorAdapter.itemCount - 1 -> {
                        outRect.top = 10f.dpToPx().toInt()
                        outRect.bottom = 0
                    }

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

        recyclerView.adapter = similarCreatorAdapter
    }

    private fun setupFanTalkView() {
        binding.layoutUserProfileFanTalk.tvAll.setOnClickListener {
            val intent = Intent(
                applicationContext,
                UserProfileFantalkAllViewActivity::class.java
            )
            intent.putExtra(Constants.EXTRA_USER_ID, userId)
            startActivity(intent)
        }

        setupCheersView()
    }

    private fun setupCheersView() {
        binding.layoutUserProfileFanTalk.ivSend.setOnClickListener {
            hideKeyboard {
                viewModel.writeCheers(
                    creatorId = userId,
                    cheersContent = binding.layoutUserProfileFanTalk.etCheer.text.toString()
                )
            }
        }

        val rvCheers = binding.layoutUserProfileFanTalk.rvCheers
        cheersAdapter = UserProfileCheersAdapter(
            userId = userId,
            enterReply = { cheersId, content ->
                hideKeyboard {
                    viewModel.writeCheers(
                        parentCheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content
                    )
                }
            },
            modifyReply = { cheersId, content ->
                hideKeyboard {
                    viewModel.modifyCheers(
                        cheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content
                    )
                }
            },
            onClickReport = { showCheersReportPopup(it) }
        )

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

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

                outRect.bottom = 0

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.top = 0
                    }

                    cheersAdapter.itemCount - 1 -> {
                        outRect.top = 10.dpToPx().toInt()
                        outRect.bottom = 10.dpToPx().toInt()
                    }

                    else -> {
                        outRect.top = 10.dpToPx().toInt()
                    }
                }
            }
        })

        rvCheers.adapter = cheersAdapter
    }

    private fun setupAudioContentListView() {
        binding.layoutUserProfileAudioContent.tvAll.setOnClickListener {
            val intent = Intent(applicationContext, AudioContentActivity::class.java)
            intent.putExtra(Constants.EXTRA_USER_ID, userId)
            startActivity(intent)
        }

        val recyclerView = binding.layoutUserProfileAudioContent.rvAudioContent
        audioContentAdapter = AudioContentAdapter {
            val intent = Intent(applicationContext, AudioContentDetailActivity::class.java)
                .apply {
                    putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it)
                }
            startActivity(intent)
        }

        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)

                when (parent.getChildAdapterPosition(view)) {
                    audioContentAdapter.itemCount - 1 -> {
                        outRect.bottom = 0
                    }

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

        recyclerView.adapter = audioContentAdapter
    }

    private fun showCheersReportPopup(cheersId: Long) {
        val dialog = CheersReportDialog(this, layoutInflater) {
            if (it.isBlank()) {
                Toast.makeText(
                    applicationContext,
                    "신고 이유를 선택해 주세요.",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                viewModel.cheersReport(cheersId, reason = it)
            }
        }

        dialog.show(screenWidth)
    }

    private fun bindData() {
        liveViewModel.toastLiveData.observe(this) {
            it?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show() }
        }

        liveViewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth, "")
            } else {
                loadingDialog.dismiss()
            }
        }

        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.creatorProfileLiveData.observe(this) {
            setCheers(it.cheers)
            setCreatorProfile(it.creator)
            setCreatorNotice(it.notice, it.creator.creatorId)
            setAudioContentList(it.contentList)
            setLiveRoomList(it.liveRoomList)
            setSimilarCreatorList(it.similarCreatorList)
            setUserDonationRanking(it.userDonationRanking)
            setActivitySummary(it.activitySummary)
        }

        viewModel.isExpandNotice.observe(this) {
            if (it) {
                binding.tvNotice.maxLines = Int.MAX_VALUE
            } else {
                binding.tvNotice.maxLines = 1
            }
        }
    }

    private fun setActivitySummary(activitySummary: GetCreatorActivitySummary) {
        binding.tvLiveCount.text = activitySummary.liveCount.moneyFormat()
        binding.tvLiveContributorCount.text = activitySummary.liveContributorCount.moneyFormat()
        binding.tvLiveTime.text = activitySummary.liveTime.moneyFormat()
        binding.tvContentCount.text = activitySummary.contentCount.moneyFormat()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setCheers(cheers: GetCheersResponse) {
        binding.layoutUserProfileFanTalk.etCheer.setText("")
        cheersAdapter.items.clear()
        binding.layoutUserProfileFanTalk.tvCheersCount.text = cheers.totalCount.toString()
        cheersAdapter.items.addAll(cheers.cheers)
        cheersAdapter.notifyDataSetChanged()

        if (cheersAdapter.itemCount <= 0) {
            binding.layoutUserProfileFanTalk.rvCheers.visibility = View.GONE
            binding.layoutUserProfileFanTalk.tvNoCheers.visibility = View.VISIBLE
        } else {
            binding.layoutUserProfileFanTalk.rvCheers.visibility = View.VISIBLE
            binding.layoutUserProfileFanTalk.tvNoCheers.visibility = View.GONE
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setCreatorProfile(creator: CreatorResponse) {
        val layoutUserProfile = binding.layoutUserProfile

        if (creator.creatorId == SharedPreferenceManager.userId) {
            layoutUserProfile.tvFollowerList.visibility = View.VISIBLE
            layoutUserProfile.llNotification.visibility = View.GONE

            layoutUserProfile.tvFollowerList.setOnClickListener {
                val intent = Intent(applicationContext, UserFollowerListActivity::class.java)
                intent.putExtra(Constants.EXTRA_USER_ID, creator.creatorId)
                startActivity(intent)
            }
        } else {
            layoutUserProfile.llNotification.visibility = View.VISIBLE
            layoutUserProfile.tvFollowerList.visibility = View.GONE
        }

        layoutUserProfile.ivProfile.load(creator.profileUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(CircleCropTransformation())
        }

        binding.tvBack.text = "${creator.nickname}님의 채널"
        layoutUserProfile.tvNickname.text = creator.nickname
        layoutUserProfile.tvTags.text = creator.tags.joinToString(" ") { "#$it" }

        if (creator.websiteUrl.isNullOrBlank() || !URLUtil.isValidUrl(creator.websiteUrl)) {
            layoutUserProfile.ivWebsite.visibility = View.GONE
        } else {
            layoutUserProfile.ivWebsite.visibility = View.VISIBLE
            layoutUserProfile.ivWebsite.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(creator.websiteUrl)))
            }
        }

        if (creator.blogUrl.isNullOrBlank() || !URLUtil.isValidUrl(creator.blogUrl)) {
            layoutUserProfile.ivBlog.visibility = View.GONE
        } else {
            layoutUserProfile.ivBlog.visibility = View.VISIBLE
            layoutUserProfile.ivBlog.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(creator.blogUrl)))
            }
        }

        if (creator.instagramUrl.isNullOrBlank() || !URLUtil.isValidUrl(creator.instagramUrl)) {
            layoutUserProfile.ivInstagram.visibility = View.GONE
        } else {
            layoutUserProfile.ivInstagram.visibility = View.VISIBLE
            layoutUserProfile.ivInstagram.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(creator.instagramUrl)))
            }
        }

        if (creator.youtubeUrl.isNullOrBlank() || !URLUtil.isValidUrl(creator.youtubeUrl)) {
            layoutUserProfile.ivYoutube.visibility = View.GONE
        } else {
            layoutUserProfile.ivYoutube.visibility = View.VISIBLE
            layoutUserProfile.ivYoutube.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(creator.youtubeUrl)))
            }
        }

        if (creator.isNotification) {
            layoutUserProfile.ivNotification.setImageResource(R.drawable.btn_notification_selected)
            layoutUserProfile.ivNotification.setOnClickListener {
                viewModel.unFollow(creator.creatorId)
            }
        } else {
            layoutUserProfile.ivNotification.setImageResource(R.drawable.btn_notification)
            layoutUserProfile.ivNotification.setOnClickListener {
                viewModel.follow(creator.creatorId)
            }
        }

        layoutUserProfile
            .tvNotificationCount
            .text = "팔로워 ${creator.notificationRecipientCount.moneyFormat()}명"

        val introduce = creator.introduce.ifBlank {
            "채널 소개내용이 없습니다."
        }

        binding.layoutUserProfileIntroduce.tvIntroduce.text = introduce
    }

    private fun setCreatorNotice(notice: String, creatorId: Long) {
        binding.tvNotice.text = notice.ifBlank {
            "공지사항이 없습니다."
        }

        binding.rlNotice.setOnClickListener {
            if (creatorId == SharedPreferenceManager.userId) {
                val intent = Intent(applicationContext, CreatorNoticeWriteActivity::class.java)
                intent.putExtra("notice", notice)
                noticeWriteLauncher.launch(intent)
            } else {
                viewModel.toggleExpandNotice()
            }
        }

        binding.ivWrite.visibility = if (creatorId == SharedPreferenceManager.userId) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setAudioContentList(audioContentList: List<GetAudioContentListItem>) {
        binding.layoutUserProfileAudioContent.root.visibility =
            if (userId == SharedPreferenceManager.userId || audioContentList.isNotEmpty()) {
                View.VISIBLE
            } else {
                View.GONE
            }

        if (userId == SharedPreferenceManager.userId) {
            binding.layoutUserProfileAudioContent.tvTitle.text = "내 콘텐츠"
            binding.layoutUserProfileAudioContent.tvNewContent.setOnClickListener {
                startActivity(
                    Intent(
                        applicationContext,
                        AudioContentUploadActivity::class.java
                    )
                )
            }
            binding.layoutUserProfileAudioContent.tvNewContent.visibility = View.VISIBLE
        } else {
            binding.layoutUserProfileAudioContent.tvTitle.text = "콘텐츠"
            binding.layoutUserProfileAudioContent.tvNewContent.visibility = View.GONE
        }

        audioContentAdapter.items.clear()
        audioContentAdapter.items.addAll(audioContentList)
        audioContentAdapter.notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setLiveRoomList(liveRoomList: List<LiveRoomResponse>) {
        if (liveRoomList.isEmpty()) {
            binding.layoutUserProfileLive.root.visibility = View.GONE
        } else {
            binding.layoutUserProfileLive.root.visibility = View.VISIBLE
            liveAdapter.items.clear()
            liveAdapter.items.addAll(liveRoomList)
            liveAdapter.notifyDataSetChanged()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setSimilarCreatorList(similarCreatorList: List<SimilarCreatorResponse>) {
        if (similarCreatorList.isEmpty()) {
            binding.llUserProfileSimilarCreator.visibility = View.GONE
        } else {
            binding.llUserProfileSimilarCreator.visibility = View.VISIBLE
            similarCreatorAdapter.items.clear()
            similarCreatorAdapter.items.addAll(similarCreatorList)
            similarCreatorAdapter.notifyDataSetChanged()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setUserDonationRanking(userDonationRanking: List<UserDonationRankingResponse>) {
        if (userDonationRanking.isEmpty()) {
            binding.llUserProfileDonation.visibility = View.GONE
        } else {
            binding.llUserProfileDonation.visibility = View.VISIBLE
            donationAdapter.items.clear()
            donationAdapter.items.addAll(userDonationRanking)
            donationAdapter.notifyDataSetChanged()
        }
    }

    private fun reservationRoom(roomId: Long) {
        liveViewModel.getRoomDetail(roomId) {
            if (it.manager.id == SharedPreferenceManager.userId) {
                showToast("내가 만든 라이브는 예약할 수 없습니다.")
            } else {
                if (it.isPrivateRoom) {
                    LiveRoomPasswordDialog(
                        activity = this,
                        layoutInflater = layoutInflater,
                        can = if (it.isPaid) 0 else it.price,
                        confirmButtonClick = { password ->
                            handler.postDelayed({
                                processLiveReservation(roomId, password)
                            }, 300)
                        }
                    ).show(screenWidth)
                } else {
                    if (it.price == 0 || it.isPaid) {
                        processLiveReservation(roomId)
                    } else {
                        LivePaymentDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            title = "${it.price.moneyFormat()}캔으로 예약",
                            desc = "'${it.title}' 라이브에 참여하기 위해 결제합니다.",
                            confirmButtonTitle = "예약하기",
                            confirmButtonClick = { processLiveReservation(roomId) },
                            cancelButtonTitle = "취소",
                            cancelButtonClick = {}
                        ).show(screenWidth)
                    }
                }
            }
        }
    }

    private fun processLiveReservation(roomId: Long, password: String? = null) {
        liveViewModel.reservationRoom(roomId, password) {
            val intent = Intent(
                applicationContext,
                LiveReservationCompleteActivity::class.java
            )
            intent.putExtra(Constants.EXTRA_LIVE_RESERVATION_RESPONSE, it)
            startActivity(intent)
        }
    }

    private fun enterLiveRoom(roomId: Long) {
        val onEnterRoomSuccess = {
            runOnUiThread {
                val intent = Intent(applicationContext, LiveRoomActivity::class.java)
                intent.putExtra(Constants.EXTRA_ROOM_ID, roomId)
                startActivity(intent)
            }
        }

        liveViewModel.getRoomDetail(roomId) {
            if (it.channelName != null) {
                if (it.manager.id == SharedPreferenceManager.userId) {
                    liveViewModel.enterRoom(roomId, onEnterRoomSuccess)
                } else if (it.price == 0 || it.isPaid) {
                    if (it.isPrivateRoom) {
                        LiveRoomPasswordDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            can = 0,
                            confirmButtonClick = { password ->
                                liveViewModel.enterRoom(
                                    roomId = roomId,
                                    onSuccess = onEnterRoomSuccess,
                                    password = password
                                )
                            }
                        ).show(screenWidth)
                    } else {
                        liveViewModel.enterRoom(roomId, onEnterRoomSuccess)
                    }
                } else {
                    if (it.isPrivateRoom) {
                        LiveRoomPasswordDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            can = it.price,
                            confirmButtonClick = { password ->
                                liveViewModel.enterRoom(
                                    roomId = roomId,
                                    onSuccess = onEnterRoomSuccess,
                                    password = password
                                )
                            }
                        ).show(screenWidth)
                    } else {
                        LivePaymentDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            title = "${it.price.moneyFormat()}캔으로 입장",
                            desc = "'${it.title}' 라이브에 참여하기 위해 결제합니다.",
                            confirmButtonTitle = "결제 후 입장",
                            confirmButtonClick = {
                                liveViewModel.enterRoom(roomId, onEnterRoomSuccess)
                            },
                            cancelButtonTitle = "취소",
                            cancelButtonClick = {}
                        ).show(screenWidth)
                    }
                }
            }
        }
    }
}
