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

import android.annotation.SuppressLint
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.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.webkit.URLUtil
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.BlurTransformation
import coil.transform.CircleCropTransformation
import coil.transform.RoundedCornersTransformation
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.series.GetSeriesListResponse
import kr.co.vividnext.sodalive.audio_content.series.SeriesListAllActivity
import kr.co.vividnext.sodalive.audio_content.series.detail.SeriesDetailActivity
import kr.co.vividnext.sodalive.audio_content.upload.AudioContentUploadActivity
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.base.SodaDialog
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.databinding.ItemCreatorCommunityBinding
import kr.co.vividnext.sodalive.dialog.MemberProfileDialog
import kr.co.vividnext.sodalive.explorer.profile.cheers.UserProfileCheersAdapter
import kr.co.vividnext.sodalive.explorer.profile.creator_community.GetCommunityPostListResponse
import kr.co.vividnext.sodalive.explorer.profile.creator_community.all.CreatorCommunityAllActivity
import kr.co.vividnext.sodalive.explorer.profile.creator_community.write.CreatorCommunityWriteActivity
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.explorer.profile.series.UserProfileSeriesListAdapter
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.loadUrl
import kr.co.vividnext.sodalive.extensions.moneyFormat
import kr.co.vividnext.sodalive.live.LiveViewModel
import kr.co.vividnext.sodalive.live.room.menu.MenuConfigActivity
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.live.roulette.config.RouletteConfigActivity
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
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

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 seriesAdapter: UserProfileSeriesListAdapter
    private lateinit var donationAdapter: UserProfileDonationAdapter
    private lateinit var cheersAdapter: UserProfileCheersAdapter

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

    private var notifyFragment: CreatorFollowNotifyFragment? = null

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

        imm = getSystemService(Service.INPUT_METHOD_SERVICE) as InputMethodManager
        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()
        setupFanTalkView()
        setupSeriesListView()
        setupAudioContentListView()
        setupCreatorCommunityView()
    }

    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 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
                    )
                }
            },
            modifyCheers = { cheersId, content ->
                hideKeyboard {
                    viewModel.modifyCheers(
                        cheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content,
                    )
                }
            },
            onClickReport = { showCheersReportPopup(it) },
            onClickDelete = {
                SodaDialog(
                    activity = this@UserProfileActivity,
                    layoutInflater = layoutInflater,
                    title = "응원글 삭제",
                    desc = "삭제하시겠습니까?",
                    confirmButtonTitle = "삭제",
                    confirmButtonClick = {
                        viewModel.modifyCheers(
                            cheersId = it,
                            creatorId = userId,
                            isActive = false
                        )
                    },
                    cancelButtonTitle = "취소",
                    cancelButtonClick = {}
                ).show(screenWidth)
            },
            onClickProfile = {
                MemberProfileDialog(
                    activity = this@UserProfileActivity,
                    layoutInflater = layoutInflater,
                    memberId = it,
                    screenWidth = screenWidth
                ).show()
            }
        )

        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 setupSeriesListView() {
        binding.layoutCreatorChannelSeries.tvAll.setOnClickListener {
            startActivity(
                Intent(applicationContext, SeriesListAllActivity::class.java).apply {
                    putExtra(Constants.EXTRA_USER_ID, userId)
                }
            )
        }

        val recyclerView = binding.layoutCreatorChannelSeries.rvSeries
        recyclerView.layoutManager = LinearLayoutManager(
            applicationContext,
            LinearLayoutManager.HORIZONTAL,
            false
        )

        seriesAdapter = UserProfileSeriesListAdapter(
            onClickItem = {
                startActivity(
                    Intent(applicationContext, SeriesDetailActivity::class.java).apply {
                        putExtra(Constants.EXTRA_SERIES_ID, it)
                    }
                )
            },
            onClickCreator = {},
            isVisibleCreator = 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()
                    }

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

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

        recyclerView.adapter = seriesAdapter
    }

    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 setupCreatorCommunityView() {
        binding.layoutCreatorCommunityPost.ivWrite.setOnClickListener {
            startActivity(Intent(applicationContext, CreatorCommunityWriteActivity::class.java))
        }
        binding.layoutCreatorCommunityPost.llAll.setOnClickListener {
            startActivity(
                Intent(applicationContext, CreatorCommunityAllActivity::class.java).apply {
                    putExtra(Constants.EXTRA_COMMUNITY_CREATOR_ID, userId)
                }
            )
        }
    }

    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)
            setSeriesList(it.seriesList)
            setCreatorProfile(it.creator)
            setAudioContentList(it.contentList)
            setLiveRoomList(it.liveRoomList)
            setUserDonationRanking(it.userDonationRanking)
            setActivitySummary(it.activitySummary)
            setCommunityPostList(it.communityPostList)
        }
    }

    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("NotifyDataSetChanged")
    private fun setSeriesList(seriesList: List<GetSeriesListResponse.SeriesListItem>) {
        if (seriesList.isNotEmpty()) {
            binding.layoutCreatorChannelSeries.root.visibility = View.VISIBLE
        } else {
            binding.layoutCreatorChannelSeries.root.visibility = View.GONE
        }

        seriesAdapter.items.clear()
        seriesAdapter.items.addAll(seriesList)
        seriesAdapter.notifyDataSetChanged()
    }

    @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.isFollow) {
            layoutUserProfile.ivNotification.setImageResource(
                if (creator.isNotify) {
                    R.drawable.btn_following_big
                } else {
                    R.drawable.btn_following_no_alarm_big
                }
            )

            layoutUserProfile.ivNotification.setOnClickListener {
                if (notifyFragment == null) {
                    notifyFragment = CreatorFollowNotifyFragment(
                        onClickNotifyAll = {
                            viewModel.follow(creator.creatorId, follow = true, notify = true)
                        },
                        onClickNotifyNone = {
                            viewModel.follow(creator.creatorId, follow = true, notify = false)
                        },
                        onClickUnFollow = {
                            viewModel.follow(creator.creatorId, follow = false, notify = false)
                        }
                    )
                }

                if (notifyFragment!!.isAdded) return@setOnClickListener
                notifyFragment!!.show(supportFragmentManager, notifyFragment!!.tag)
            }
        } else {
            layoutUserProfile.ivNotification.setImageResource(R.drawable.btn_follow_big)
            layoutUserProfile.ivNotification.setOnClickListener {
                viewModel.follow(creator.creatorId)
            }
        }

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

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

        binding.layoutUserProfileIntroduce.tvIntroduce.text = introduce
    }

    @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 (userId == SharedPreferenceManager.userId) {
            binding.layoutUserProfileLive.root.visibility = View.VISIBLE
            binding.layoutUserProfileLive.llRouletteMenu.visibility = View.VISIBLE

            if (liveRoomList.isEmpty()) {
                binding.layoutUserProfileLive.rvLive.visibility = View.GONE
            } else {
                binding.layoutUserProfileLive.rvLive.visibility = View.VISIBLE
            }

            binding.layoutUserProfileLive.tvSettingRoulette.setOnClickListener {
                startActivity(
                    Intent(applicationContext, RouletteConfigActivity::class.java).apply {
                        putExtra(Constants.EXTRA_ROULETTE_AVAILABLE_ACTIVE, false)
                    }
                )
            }

            binding.layoutUserProfileLive.tvSettingMenu.setOnClickListener {
                startActivity(
                    Intent(applicationContext, MenuConfigActivity::class.java)
                )
            }
        } else {
            binding.layoutUserProfileLive.llRouletteMenu.visibility = View.GONE

            if (liveRoomList.isEmpty()) {
                binding.layoutUserProfileLive.root.visibility = View.GONE
            } else {
                binding.layoutUserProfileLive.root.visibility = View.VISIBLE
                binding.layoutUserProfileLive.rvLive.visibility = View.VISIBLE
            }
        }

        if (liveRoomList.isNotEmpty()) {
            liveAdapter.items.clear()
            liveAdapter.items.addAll(liveRoomList)
            liveAdapter.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 setCommunityPostList(communityPostList: List<GetCommunityPostListResponse>) {
        if (communityPostList.isEmpty()) {
            if (userId == SharedPreferenceManager.userId) {
                binding.layoutCreatorCommunityPost.root.visibility = View.VISIBLE
                binding.layoutCreatorCommunityPost.llNoPost.visibility = View.VISIBLE
                binding.layoutCreatorCommunityPost.llNoPost.setOnClickListener {
                    startActivity(
                        Intent(
                            applicationContext,
                            CreatorCommunityWriteActivity::class.java
                        )
                    )
                }
            } else {
                binding.layoutCreatorCommunityPost.root.visibility = View.GONE
            }

            binding.layoutCreatorCommunityPost.hsvPost.visibility = View.GONE
        } else {
            binding.layoutCreatorCommunityPost.root.visibility = View.VISIBLE
            binding.layoutCreatorCommunityPost.llNoPost.visibility = View.GONE
            binding.layoutCreatorCommunityPost.hsvPost.visibility = View.VISIBLE

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

            binding.layoutCreatorCommunityPost.llContainer.removeAllViews()
            communityPostList.forEachIndexed { index, item ->
                val layout = ItemCreatorCommunityBinding.inflate(
                    LayoutInflater.from(this@UserProfileActivity),
                    binding.layoutCreatorCommunityPost.llContainer,
                    false
                )

                setCommunityPost(layout, item, index)
            }
        }
    }

    private fun setCommunityPost(
        layout: ItemCreatorCommunityBinding,
        item: GetCommunityPostListResponse,
        index: Int
    ) {
        layout.ivCreatorProfile.loadUrl(item.creatorProfileUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(CircleCropTransformation())
        }
        layout.tvCreatorNickname.text = item.creatorNickname
        layout.tvDate.text = item.date

        layout.tvContent.text = item.content
        layout.ivPostImage.loadUrl(item.imageUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(RoundedCornersTransformation(4.7f.dpToPx()))

            if (!item.existOrdered && item.price > 0) {
                transformations(
                    BlurTransformation(
                        this@UserProfileActivity,
                        25f,
                        2.5f
                    )
                )
            }
        }

        layout.tvLikeCount.text = "${item.likeCount}"
        layout.tvCommentCount.text = "${item.commentCount}"

        layout.root.setOnClickListener {
            startActivity(
                Intent(applicationContext, CreatorCommunityAllActivity::class.java).apply {
                    putExtra(Constants.EXTRA_COMMUNITY_CREATOR_ID, userId)
                }
            )
        }

        if (index > 0) {
            val lp = layout.root.layoutParams as LinearLayout.LayoutParams
            lp.marginStart = 13.3f.dpToPx().toInt()
            layout.root.layoutParams = lp
        }

        binding.layoutCreatorCommunityPost.llContainer.addView(layout.root)
    }

    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 {
                    val beginDateFormat = SimpleDateFormat("yyyy.MM.dd EEE hh:mm a", Locale.ENGLISH)
                    val beginDate = beginDateFormat.parse(it.beginDateTime)!!
                    val now = Date()

                    val dateFormat = SimpleDateFormat("yyyy-MM-dd, HH:mm", Locale.getDefault())
                    val diffTime: Long = now.time - beginDate.time
                    val hours = (diffTime / (1000 * 60 * 60)).toInt()
                    val mins = (diffTime / (1000 * 60)).toInt() % 60

                    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 = "유료 라이브 입장",
                            startDateTime = if (hours >= 1) {
                                dateFormat.format(beginDate)
                            } else {
                                null
                            },
                            nowDateTime = if (hours >= 1) {
                                dateFormat.format(now)
                            } else {
                                null
                            },
                            desc = "${it.price}캔을 차감하고\n라이브에 입장 하시겠습니까?",
                            desc2 = if (hours >= 1) {
                                "라이브를 시작한 지 ${hours}시간 ${mins}분이 지났습니다. 라이브에 입장 후 30분 이내에 라이브가 종료될 수도 있습니다."
                            } else {
                                null
                            },
                            confirmButtonTitle = "결제 후 입장",
                            confirmButtonClick = {
                                liveViewModel.enterRoom(roomId, onEnterRoomSuccess)
                            },
                            cancelButtonTitle = "취소",
                            cancelButtonClick = {}
                        ).show(screenWidth)
                    }
                }
            }
        }
    }
}
