package kr.co.vividnext.sodalive.live.now.all

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.audio_content.AudioContentPlayService
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.ActivityLiveNowAllBinding
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.room.LiveRoomActivity
import kr.co.vividnext.sodalive.live.room.detail.LiveRoomDetailFragment
import kr.co.vividnext.sodalive.live.room.dialog.LivePaymentDialog
import kr.co.vividnext.sodalive.live.room.dialog.LiveRoomPasswordDialog
import org.koin.android.ext.android.inject

class LiveNowAllActivity : BaseActivity<ActivityLiveNowAllBinding>(
    ActivityLiveNowAllBinding::inflate
) {
    private val viewModel: LiveViewModel by inject()

    private lateinit var adapter: LiveNowAllAdapter
    private lateinit var loadingDialog: LoadingDialog

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

        bindData()
        viewModel.getLiveNow()
    }

    override fun setupView() {
        binding.toolbar.tvBack.text = "지금 라이브 중 전체보기"
        binding.toolbar.tvBack.setOnClickListener { finish() }
        loadingDialog = LoadingDialog(this, layoutInflater)

        val recyclerView = binding.rvLive
        adapter = LiveNowAllAdapter {
            val detailFragment = LiveRoomDetailFragment(
                it.roomId,
                onClickParticipant = { enterLiveRoom(it.roomId) },
                onClickReservation = {},
                onClickModify = {},
                onClickStart = {},
                onClickCancel = {}
            )

            detailFragment.show(
                supportFragmentManager,
                detailFragment.tag
            )
        }

        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.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }

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

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

        recyclerView.adapter = adapter

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

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

                if (lastVisiblePosition == itemTotalCount) {
                    viewModel.getLiveNow()
                }
            }
        })

        binding.swipeRefreshLayout.setOnRefreshListener {
            adapter.clear()
            viewModel.page = 1
            viewModel.isLast = false
            viewModel.getLiveNow()

            binding.swipeRefreshLayout.isRefreshing = false
        }
    }

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

        val onEnterRoomSuccess = {
            runOnUiThread {
                val intent = Intent(applicationContext, 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) {
                    viewModel.enterRoom(roomId, onEnterRoomSuccess)
                } else if (it.price == 0 || it.isPaid) {
                    if (it.isPrivateRoom) {
                        LiveRoomPasswordDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            can = 0,
                            confirmButtonClick = { password ->
                                viewModel.enterRoom(
                                    roomId = roomId,
                                    onSuccess = onEnterRoomSuccess,
                                    password = password
                                )
                            }
                        ).show(screenWidth)
                    } else {
                        viewModel.enterRoom(roomId, onEnterRoomSuccess)
                    }
                } else {
                    if (it.isPrivateRoom) {
                        LiveRoomPasswordDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            can = it.price,
                            confirmButtonClick = { password ->
                                viewModel.enterRoom(
                                    roomId = roomId,
                                    onSuccess = onEnterRoomSuccess,
                                    password = password
                                )
                            }
                        ).show(screenWidth)
                    } else {
                        LivePaymentDialog(
                            activity = this,
                            layoutInflater = layoutInflater,
                            title = "${it.price.moneyFormat()} 캔으로 입장",
                            desc = "'${it.title}' 라이브에 참여하기 위해 결제합니다.",
                            confirmButtonTitle = "결제 후 입장",
                            confirmButtonClick = {
                                viewModel.enterRoom(roomId, onEnterRoomSuccess)
                            },
                            cancelButtonTitle = "취소",
                            cancelButtonClick = {}
                        ).show(screenWidth)
                    }
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.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.liveNowLiveData.observe(this) {
            if (it.isEmpty()) {
                if (adapter.items.isEmpty()) {
                    binding.rvLive.visibility = View.GONE
                    binding.tvNoItems.visibility = View.VISIBLE
                }
            } else {
                binding.rvLive.visibility = View.VISIBLE
                binding.tvNoItems.visibility = View.GONE
                adapter.items.addAll(it)
                adapter.notifyDataSetChanged()
            }
        }
    }
}
