package kr.co.vividnext.sodalive.live

import android.annotation.SuppressLint
import android.app.Activity
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.widget.LinearLayout
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.AudioContentPlayService
import kr.co.vividnext.sodalive.audio_content.all.by_theme.AudioContentAllByThemeActivity
import kr.co.vividnext.sodalive.base.BaseFragment
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.FragmentLiveBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import kr.co.vividnext.sodalive.explorer.profile.creator_community.CreatorCommunityAdapter
import kr.co.vividnext.sodalive.explorer.profile.creator_community.all.CreatorCommunityAllActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat
import kr.co.vividnext.sodalive.following.FollowingCreatorActivity
import kr.co.vividnext.sodalive.live.event_banner.EventBannerAdapter
import kr.co.vividnext.sodalive.live.now.LiveNowAdapter
import kr.co.vividnext.sodalive.live.now.all.LiveNowAllActivity
import kr.co.vividnext.sodalive.live.recommend.RecommendLiveAdapter
import kr.co.vividnext.sodalive.live.recommend_channel.LiveRecommendChannelAdapter
import kr.co.vividnext.sodalive.live.reservation.LiveReservationAdapter
import kr.co.vividnext.sodalive.live.reservation.all.LiveReservationAllActivity
import kr.co.vividnext.sodalive.live.reservation.complete.LiveReservationCompleteActivity
import kr.co.vividnext.sodalive.live.room.LiveRoomActivity
import kr.co.vividnext.sodalive.live.room.create.LiveRoomCreateActivity
import kr.co.vividnext.sodalive.live.room.detail.GetRoomDetailResponse
import kr.co.vividnext.sodalive.live.room.detail.LiveRoomDetailFragment
import kr.co.vividnext.sodalive.live.room.dialog.LiveCancelDialog
import kr.co.vividnext.sodalive.live.room.dialog.LivePaymentDialog
import kr.co.vividnext.sodalive.live.room.dialog.LiveRoomPasswordDialog
import kr.co.vividnext.sodalive.live.room.update.LiveRoomEditActivity
import kr.co.vividnext.sodalive.settings.event.EventDetailActivity
import kr.co.vividnext.sodalive.settings.notification.MemberRole
import org.koin.android.ext.android.inject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt

class LiveFragment : BaseFragment<FragmentLiveBinding>(FragmentLiveBinding::inflate) {
    private val viewModel: LiveViewModel by inject()

    private lateinit var liveNowAdapter: LiveNowAdapter
    private lateinit var liveReservationAdapter: LiveReservationAdapter
    private lateinit var creatorCommunityAdapter: CreatorCommunityAdapter
    private lateinit var liveRecommendChannelAdapter: LiveRecommendChannelAdapter

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

    private var message = ""
    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        activityResultLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                val roomId = it.data?.getLongExtra(Constants.EXTRA_ROOM_ID, 0)
                val channelName = it.data?.getStringExtra(Constants.EXTRA_ROOM_CHANNEL_NAME)
                refreshSummary()

                if (channelName != null) {
                    enterLiveRoom(roomId = roomId!!)
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupView()
        setupRecommendLive()
        setupRecommendChannel()
        setupLiveNow()
        setupLiveReservation()
        setupEvent()
        setupCommunityPost()

        binding.llReviewLive.setOnClickListener {
            startActivity(
                Intent(requireContext(), AudioContentAllByThemeActivity::class.java).apply {
                    putExtra(Constants.EXTRA_THEME_ID, 7L)
                }
            )
        }

        message = "라이브를 불러오고 있습니다."
        viewModel.getSummary()
    }

    private fun setupView() {
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)

        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { Toast.makeText(requireActivity(), it, Toast.LENGTH_LONG).show() }
        }

        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth, message)
            } else {
                loadingDialog.dismiss()
            }
        }

        binding.ivMakeRoom.visibility =
            if (SharedPreferenceManager.role == MemberRole.CREATOR.name) {
                View.VISIBLE
            } else {
                View.GONE
            }

        binding.ivMakeRoom.setOnClickListener {
            val intent = Intent(requireContext(), LiveRoomCreateActivity::class.java)
            activityResultLauncher.launch(intent)
        }
    }

    private fun refreshSummary() {
        liveNowAdapter.clear()
        liveRecommendChannelAdapter.clear()
        liveReservationAdapter.clear()

        message = "라이브를 불러오고 있습니다."
        viewModel.getSummary()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupRecommendLive() {
        val layoutParams = binding
            .layoutRecommendLive
            .pager
            .layoutParams as LinearLayout.LayoutParams

        val pagerWidth = screenWidth.toDouble() - 26.7f.dpToPx()
        val pagerHeight = (pagerWidth * 0.53).roundToInt()
        layoutParams.width = pagerWidth.roundToInt()
        layoutParams.height = pagerHeight

        binding
            .layoutRecommendLive
            .pager
            .layoutParams = layoutParams

        binding.layoutRecommendLive.pager.apply {
            adapter = RecommendLiveAdapter(requireContext(), pagerWidth.roundToInt(), pagerHeight) {
                startActivity(
                    Intent(requireContext(), UserProfileActivity::class.java).apply {
                        putExtra(Constants.EXTRA_USER_ID, it)
                    }
                )
            } as BaseBannerAdapter<Any>

            setLifecycleRegistry(lifecycle)
            setScrollDuration(1000)
            setInterval(4 * 1000)
        }.create()

        binding
            .layoutRecommendLive
            .pager
            .setIndicatorView(binding.layoutRecommendLive.indicator2)
            .setIndicatorStyle(IndicatorStyle.ROUND_RECT)
            .setIndicatorSlideMode(IndicatorSlideMode.SMOOTH)
            .setIndicatorVisibility(View.GONE)
            .setIndicatorSliderColor(
                ContextCompat.getColor(requireContext(), R.color.color_909090),
                ContextCompat.getColor(requireContext(), R.color.color_3bb9f1)
            )
            .setIndicatorSliderWidth(4f.dpToPx().toInt(), 10f.dpToPx().toInt())
            .setIndicatorHeight(4f.dpToPx().toInt())

        viewModel.recommendLiveData.observe(viewLifecycleOwner) {
            if (it.isNotEmpty()) {
                binding.layoutRecommendLive.root.visibility = View.VISIBLE
                binding.layoutRecommendLive.pager.refreshData(it)
            } else {
                binding.layoutRecommendLive.root.visibility = View.GONE
            }
        }
    }

    private fun setupRecommendChannel() {
        liveRecommendChannelAdapter = LiveRecommendChannelAdapter(
            onClick = {
                startActivity(
                    Intent(requireContext(), UserProfileActivity::class.java).apply {
                        putExtra(Constants.EXTRA_USER_ID, it)
                    }
                )
            },
            onClickMore = {
                startActivity(Intent(requireContext(), FollowingCreatorActivity::class.java))
            }
        )

        binding.layoutRecommendChannel.rvRecommendChannel.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.HORIZONTAL,
            false
        )

        binding
            .layoutRecommendChannel
            .rvRecommendChannel
            .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.dpToPx().toInt()
                            outRect.right = 8.3f.dpToPx().toInt()
                        }

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

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

        binding.layoutRecommendChannel.rvRecommendChannel.adapter = liveRecommendChannelAdapter
        binding.layoutRecommendChannel.ivSwitch.setOnClickListener {
            viewModel.toggleIsFollowedCreatorLive()
        }

        viewModel.recommendChannelLiveData.observe(viewLifecycleOwner) {
            binding.layoutRecommendChannel.root.visibility = View.VISIBLE
            liveRecommendChannelAdapter.addItems(it)
            binding.layoutRecommendChannel.rvRecommendChannel.requestLayout()
            binding.layoutRecommendChannel.root.requestLayout()
        }

        viewModel.isFollowedCreatorLive.observe(viewLifecycleOwner) {
            liveRecommendChannelAdapter.isFollowedCreatorLive = it
            liveRecommendChannelAdapter.clear()

            if (it) {
                binding.layoutRecommendChannel.ivSwitch.setImageResource(R.drawable.btn_toggle_on_big)
                binding.layoutRecommendChannel.llTitle2.visibility = View.VISIBLE
                binding.layoutRecommendChannel.llTitle1.visibility = View.GONE
            } else {
                binding.layoutRecommendChannel.ivSwitch.setImageResource(R.drawable.btn_toggle_off_big)
                binding.layoutRecommendChannel.llTitle1.visibility = View.VISIBLE
                binding.layoutRecommendChannel.llTitle2.visibility = View.GONE
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupLiveNow() {
        binding
            .layoutLiveNow
            .tvAllView
            .setOnClickListener {
                startActivity(Intent(requireContext(), LiveNowAllActivity::class.java))
            }

        binding
            .layoutLiveNow
            .llRefresh
            .setOnClickListener { refreshSummary() }

        val recyclerView = binding
            .layoutLiveNow
            .rvSudaNow

        liveNowAdapter = LiveNowAdapter {
            val detailFragment = LiveRoomDetailFragment(
                it.roomId,
                onClickParticipant = { enterLiveRoom(it.roomId) },
                onClickReservation = {},
                onClickModify = {},
                onClickStart = {},
                onClickCancel = {}
            )
            if (detailFragment.isAdded) return@LiveNowAdapter

            detailFragment.show(
                requireActivity().supportFragmentManager,
                detailFragment.tag
            )
        }

        recyclerView.layoutManager = LinearLayoutManager(
            requireContext(),
            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 = 13.3f.dpToPx().toInt()
                        outRect.right = 5.dpToPx().toInt()
                    }

                    liveNowAdapter.itemCount - 1 -> {
                        outRect.left = 5.dpToPx().toInt()
                        outRect.right = 13.3f.dpToPx().toInt()
                    }

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

        recyclerView.adapter = liveNowAdapter

        viewModel.liveNowLiveData.observe(viewLifecycleOwner) {
            if (liveNowAdapter.items.isEmpty() && it.isEmpty()) {
                recyclerView.visibility = View.GONE
                binding.layoutLiveNow.tvAllView.visibility = View.GONE
                binding.layoutLiveNow.llNoItems.visibility = View.VISIBLE
                recyclerView.requestLayout()
                binding.layoutLiveNow.llNoItems.requestLayout()
            } else {
                binding.layoutLiveNow.tvAllView.visibility = View.VISIBLE
                binding.layoutLiveNow.llNoItems.visibility = View.GONE
                liveNowAdapter.items.addAll(it)
                liveNowAdapter.notifyDataSetChanged()
                recyclerView.visibility = View.VISIBLE
                recyclerView.requestLayout()
            }

            binding.layoutLiveNow.root.requestLayout()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupLiveReservation() {
        val recyclerView = binding
            .layoutLiveReservation
            .rvSudaReservation

        liveReservationAdapter = LiveReservationAdapter(isMain = true) {
            val detailFragment = LiveRoomDetailFragment(
                it.roomId,
                onClickParticipant = {},
                onClickReservation = { reservationRoom(it.roomId) },
                onClickModify = { roomDetailResponse -> modifyLive(roomDetailResponse) },
                onClickStart = { startLive(it.roomId) },
                onClickCancel = { cancelLive(it.roomId) }
            )
            if (detailFragment.isAdded) return@LiveReservationAdapter

            detailFragment.show(
                requireActivity().supportFragmentManager,
                detailFragment.tag
            )
        }

        recyclerView.layoutManager = LinearLayoutManager(
            requireContext(),
            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 = 13.3f.dpToPx().toInt()
                outRect.right = 13.3f.dpToPx().toInt()

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

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

        recyclerView.adapter = liveReservationAdapter

        viewModel.liveReservationLiveData.observe(viewLifecycleOwner) {
            if (liveReservationAdapter.items.isEmpty() && it.isEmpty()) {
                recyclerView.visibility = View.GONE
                binding.layoutLiveReservation.tvAllView.visibility = View.GONE
                binding.layoutLiveReservation.llNoItems.visibility = View.VISIBLE
                recyclerView.requestLayout()
                binding.layoutLiveReservation.llNoItems.requestLayout()
            } else {
                binding.layoutLiveReservation.tvAllView.visibility = View.VISIBLE
                binding.layoutLiveReservation.llNoItems.visibility = View.GONE
                liveReservationAdapter.items.addAll(it)
                liveReservationAdapter.notifyDataSetChanged()

                recyclerView.visibility = View.VISIBLE
                recyclerView.requestLayout()
            }

            binding.layoutLiveReservation.root.requestLayout()
        }

        binding.layoutLiveReservation.tvAllView.setOnClickListener {
            startActivity(
                Intent(requireContext(), LiveReservationAllActivity::class.java)
            )
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupEvent() {
        val imageSliderLp = binding.eventBannerSlider.layoutParams
        imageSliderLp.width = screenWidth
        imageSliderLp.height = (screenWidth * 300) / 1000
        binding.eventBannerSlider.layoutParams = imageSliderLp

        binding.eventBannerSlider.apply {
            adapter = EventBannerAdapter(requireContext()) {
                if (it.detailImageUrl != null) {
                    val intent = Intent(requireActivity(), EventDetailActivity::class.java)
                    intent.putExtra(Constants.EXTRA_EVENT, it)
                    startActivity(intent)
                } else if (!it.link.isNullOrBlank()) {
                    startActivity(
                        Intent(
                            Intent.ACTION_VIEW,
                            Uri.parse(it.link)
                        )
                    )
                }
            } as BaseBannerAdapter<Any>
            setLifecycleRegistry(lifecycle)
            setScrollDuration(800)
        }.create()

        binding.eventBannerSlider
            .setIndicatorView(binding.indicator)
            .setIndicatorStyle(IndicatorStyle.ROUND_RECT)
            .setIndicatorSlideMode(IndicatorSlideMode.SMOOTH)
            .setIndicatorVisibility(View.GONE)
            .setIndicatorSliderColor(
                ContextCompat.getColor(requireContext(), R.color.color_909090),
                ContextCompat.getColor(requireContext(), R.color.color_3bb9f1)
            )
            .setIndicatorSliderWidth(4f.dpToPx().toInt(), 10f.dpToPx().toInt())
            .setIndicatorHeight(4f.dpToPx().toInt())

        viewModel.eventLiveData.observe(viewLifecycleOwner) {
            if (it.isNotEmpty()) {
                binding.eventBannerSlider.visibility = View.VISIBLE
                binding.eventBannerSlider.refreshData(it)
            } else {
                binding.eventBannerSlider.visibility = View.GONE
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupCommunityPost() {
        val recyclerView = binding.rvCommunityPost

        recyclerView.layoutManager = LinearLayoutManager(
            requireContext(),
            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 = 13.3f.dpToPx().toInt()
                        outRect.right = 5.dpToPx().toInt()
                    }

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

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

        creatorCommunityAdapter = CreatorCommunityAdapter {
            startActivity(
                Intent(
                    requireActivity(),
                    CreatorCommunityAllActivity::class.java
                ).apply {
                    putExtra(Constants.EXTRA_COMMUNITY_CREATOR_ID, it)
                }
            )
        }
        binding.rvCommunityPost.adapter = creatorCommunityAdapter

        viewModel.communityPostItemLiveData.observe(viewLifecycleOwner) {
            if (it.isNotEmpty()) {
                binding.rvCommunityPost.visibility = View.VISIBLE
                creatorCommunityAdapter.items.clear()
                creatorCommunityAdapter.items.addAll(it)
                creatorCommunityAdapter.notifyDataSetChanged()
            } else {
                binding.rvCommunityPost.visibility = View.GONE
            }
        }
    }

    private fun startLive(roomId: Long) {
        val onEnterRoomSuccess = {
            viewModel.getSummary()
            requireActivity().runOnUiThread {
                val intent = Intent(requireContext(), LiveRoomActivity::class.java)
                intent.putExtra(Constants.EXTRA_ROOM_ID, roomId)
                startActivity(intent)
            }
        }

        viewModel.startLive(roomId, onEnterRoomSuccess)
    }

    private fun cancelLive(roomId: Long) {
        LiveCancelDialog(
            activity = requireActivity(),
            layoutInflater = layoutInflater,
            title = "예약취소",
            hint = "취소사유를 입력하세요.",
            confirmButtonTitle = "예약취소",
            confirmButtonClick = {
                viewModel.cancelLive(roomId, it) {
                    Toast.makeText(
                        requireActivity(),
                        "예약이 취소되었습니다.",
                        Toast.LENGTH_LONG
                    ).show()
                    message = "라이브를 불러오고 있습니다."
                    liveNowAdapter.clear()
                    liveReservationAdapter.clear()
                    viewModel.getSummary()
                }
            },
            cancelButtonTitle = "닫기",
            cancelButtonClick = {}
        ).show(screenWidth)
    }

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

    private fun processLiveReservation(roomId: Long, password: String = "") {
        viewModel.reservationRoom(roomId, password) {
            refreshSummary()
            val intent = Intent(
                requireActivity(),
                LiveReservationCompleteActivity::class.java
            )
            intent.putExtra(Constants.EXTRA_LIVE_RESERVATION_RESPONSE, it)
            startActivity(intent)
        }
    }

    private fun modifyLive(roomDetail: GetRoomDetailResponse) {
        startActivity(
            Intent(requireContext(), LiveRoomEditActivity::class.java).apply {
                putExtra(Constants.EXTRA_ROOM_DETAIL, roomDetail)
            }
        )
    }

    fun enterLiveRoom(roomId: Long) {
        requireContext().startService(
            Intent(requireContext(), AudioContentPlayService::class.java).apply {
                action = AudioContentPlayService.MusicAction.STOP.name
            }
        )

        val onEnterRoomSuccess = {
            requireActivity().runOnUiThread {
                val intent = Intent(requireContext(), LiveRoomActivity::class.java)
                intent.putExtra(Constants.EXTRA_ROOM_ID, roomId)
                startActivity(intent)
            }
        }

        viewModel.getRoomDetail(roomId) {
            if (it.channelName != null) {
                if (it.manager.id == SharedPreferenceManager.userId) {
                    handler.postDelayed({
                        viewModel.enterRoom(roomId, onEnterRoomSuccess)
                    }, 300)
                } else if (it.price == 0 || it.isPaid) {
                    if (it.isPrivateRoom) {
                        LiveRoomPasswordDialog(
                            activity = requireActivity(),
                            layoutInflater = layoutInflater,
                            can = 0,
                            confirmButtonClick = { password ->
                                viewModel.enterRoom(
                                    roomId = roomId,
                                    onSuccess = onEnterRoomSuccess,
                                    password = password
                                )
                            }
                        ).show(screenWidth)
                    } else {
                        handler.postDelayed({
                            viewModel.enterRoom(roomId, onEnterRoomSuccess)
                        }, 300)
                    }
                } 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 = requireActivity(),
                            layoutInflater = layoutInflater,
                            can = it.price,
                            confirmButtonClick = { password ->
                                handler.postDelayed({
                                    viewModel.enterRoom(
                                        roomId = roomId,
                                        onSuccess = onEnterRoomSuccess,
                                        password = password
                                    )
                                }, 300)
                            }
                        ).show(screenWidth)
                    } else {
                        LivePaymentDialog(
                            activity = requireActivity(),
                            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 = {
                                handler.postDelayed({
                                    viewModel.enterRoom(roomId, onEnterRoomSuccess)
                                }, 300)
                            },
                            cancelButtonTitle = "취소",
                            cancelButtonClick = {}
                        ).show(screenWidth)
                    }
                }
            } else {
                val detailFragment = LiveRoomDetailFragment(
                    it.roomId,
                    onClickParticipant = {},
                    onClickReservation = { reservationRoom(it.roomId) },
                    onClickModify = { roomDetailResponse -> modifyLive(roomDetailResponse) },
                    onClickStart = { startLive(it.roomId) },
                    onClickCancel = { cancelLive(it.roomId) }
                )
                if (detailFragment.isAdded) return@getRoomDetail

                detailFragment.show(
                    requireActivity().supportFragmentManager,
                    detailFragment.tag
                )
            }
        }
    }
}
