package kr.co.vividnext.sodalive.explorer.profile.creator_community.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.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.databinding.ActivityCreatorCommunityAllBinding
import kr.co.vividnext.sodalive.explorer.profile.creator_community.all.comment.CreatorCommunityCommentFragment
import kr.co.vividnext.sodalive.explorer.profile.creator_community.all.player.CreatorCommunityMediaPlayerManager
import kr.co.vividnext.sodalive.explorer.profile.creator_community.modify.CreatorCommunityModifyActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class CreatorCommunityAllActivity : BaseActivity<ActivityCreatorCommunityAllBinding>(
    ActivityCreatorCommunityAllBinding::inflate
) {

    private val viewModel: CreatorCommunityAllViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: CreatorCommunityAllAdapter
    private lateinit var mediaPlayerManager: CreatorCommunityMediaPlayerManager

    private var creatorId: Long = 0

    private val modifyResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        val resultCode = result.resultCode

        if (resultCode == RESULT_OK) {
            viewModel.page = 1
            viewModel.isLast = false
            viewModel.getCommunityPostList()
        }
    }

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

        mediaPlayerManager = CreatorCommunityMediaPlayerManager(this) {
            adapter.updateUI()
        }

        creatorId = intent.getLongExtra(Constants.EXTRA_COMMUNITY_CREATOR_ID, 0)
        if (creatorId <= 0) {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }

        bindData()
        viewModel.creatorId = creatorId
        viewModel.getCommunityPostList()
    }

    override fun onPause() {
        mediaPlayerManager.pauseContent()
        super.onPause()
    }

    override fun onDestroy() {
        mediaPlayerManager.stopContent()
        super.onDestroy()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "커뮤니티"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        adapter = CreatorCommunityAllAdapter(
            screenWidth = screenWidth,
            onClickLike = { viewModel.communityPostLike(it) },
            writeComment = { postId, parentId, comment ->
                viewModel.registerComment(
                    comment,
                    postId,
                    parentId
                )
            },
            showCommentBottomSheetDialog = {
                val dialog = CreatorCommunityCommentFragment(
                    creatorId = creatorId,
                    postId = it
                )
                dialog.show(
                    supportFragmentManager,
                    dialog.tag
                )
            },
            onClickModify = {
                modifyResult.launch(
                    Intent(
                        applicationContext,
                        CreatorCommunityModifyActivity::class.java
                    ).apply {
                        putExtra(Constants.EXTRA_COMMUNITY_POST_ID, it)
                    }
                )
            },
            onClickDelete = { postId ->
                SodaDialog(
                    activity = this@CreatorCommunityAllActivity,
                    layoutInflater = layoutInflater,
                    title = "게시물 삭제",
                    desc = "삭제하시겠습니까?",
                    confirmButtonTitle = "삭제",
                    confirmButtonClick = {
                        viewModel.deleteCommunityPostList(postId = postId)
                    },
                    cancelButtonTitle = "취소",
                    cancelButtonClick = {}
                ).show(screenWidth)
            },
            onClickReport = { postId ->
                CreatorCommunityReportDialog(this@CreatorCommunityAllActivity, layoutInflater) {
                    viewModel.report(
                        communityPostId = postId,
                        reason = it
                    )
                }.show(screenWidth)
            },
            onClickAudioContentPlayOrPause = { mediaPlayerManager.toggleContent(it) },
            isAudioContentPlaying = { mediaPlayerManager.isPlayingContent(it) },
            onClickPurchaseContent = { postId, can, onSuccess ->
                PurchaseCommunityPostDialog(
                    activity = this@CreatorCommunityAllActivity,
                    layoutInflater = layoutInflater,
                    can = can,
                    confirmButtonClick = {
                        viewModel.purchaseCommunityPost(postId) {
                            onSuccess(it)
                        }
                    }
                ).show(screenWidth)
            }
        )

        val recyclerView = binding.rvCreatorCommunity
        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)

                outRect.left = 6.7f.dpToPx().toInt()
                outRect.right = 6.7f.dpToPx().toInt()

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

                    adapter.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.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 (itemTotalCount > 0 && lastVisiblePosition == itemTotalCount) {
                    viewModel.getCommunityPostList()
                }
            }
        })

        recyclerView.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        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.communityPostListLiveData.observe(this) {
            if (viewModel.page == 2) {
                adapter.items.clear()
            }

            adapter.items.addAll(it)
            adapter.notifyDataSetChanged()
        }
    }
}
