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

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
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.GridSpacingItemDecoration
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.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
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

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 spanCount = 3
        val spacing = 40
        val recyclerView = binding.rvLive
        adapter = LiveNowAllAdapter(itemWidth = (screenWidth - (spacing * (spanCount + 1))) / 3) {
            val detailFragment = LiveRoomDetailFragment(
                it.roomId,
                onClickParticipant = { enterLiveRoom(it.roomId) },
                onClickReservation = {},
                onClickModify = {},
                onClickStart = {},
                onClickCancel = {}
            )

            detailFragment.show(
                supportFragmentManager,
                detailFragment.tag
            )
        }

        recyclerView.layoutManager = GridLayoutManager(this, spanCount)
        recyclerView.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, false))

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

        recyclerView.adapter = adapter

        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 {
                    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 ->
                                viewModel.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.moneyFormat()}캔을 차감하고\n라이브에 입장 하시겠습니까?",
                            desc2 = if (hours >= 1) {
                                "라이브를 시작한 지 ${hours}시간 ${mins}분이 지났습니다. 라이브에 입장 후 30분 이내에 라이브가 종료될 수도 있습니다."
                            } else {
                                null
                            },
                            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()
            }
        }
    }
}
