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

import android.annotation.SuppressLint
import android.app.Service
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
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.ActivityUserProfileFantalkAllBinding
import kr.co.vividnext.sodalive.dialog.MemberProfileDialog
import kr.co.vividnext.sodalive.explorer.profile.cheers.UserProfileCheersAdapter
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.report.CheersReportDialog
import org.koin.android.ext.android.inject

class UserProfileFantalkAllViewActivity : BaseActivity<ActivityUserProfileFantalkAllBinding>(
    ActivityUserProfileFantalkAllBinding::inflate
) {
    private val viewModel: UserProfileFantalkAllViewModel by inject()

    private lateinit var imm: InputMethodManager
    private lateinit var loadingDialog: LoadingDialog
    private lateinit var cheersAdapter: UserProfileCheersAdapter

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

    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) {
            bindData()

            viewModel.getCheersList(creatorId = userId)
        } else {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "팬 Talk 전체보기"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        setupCheersView()
    }

    private fun setupCheersView() {
        binding.ivSend.setOnClickListener {
            hideKeyboard {
                cheersAdapter.items.clear()
                viewModel.writeCheers(
                    creatorId = userId,
                    cheersContent = binding.etCheer.text.toString()
                )
            }
        }

        val rvCheers = binding.rvCheers
        cheersAdapter = UserProfileCheersAdapter(
            userId = userId,
            enterReply = { cheersId, content ->
                hideKeyboard {
                    cheersAdapter.items.clear()
                    viewModel.writeCheers(
                        parentCheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content
                    )
                }
            },
            modifyReply = { cheersId, content ->
                hideKeyboard {
                    cheersAdapter.items.clear()
                    viewModel.modifyCheers(
                        cheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content
                    )
                }
            },
            modifyCheers = { cheersId, content ->
                hideKeyboard {
                    cheersAdapter.items.clear()
                    viewModel.modifyCheers(
                        cheersId = cheersId,
                        creatorId = userId,
                        cheersContent = content,
                    )
                }
            },
            onClickReport = { showCheersReportPopup(it) },
            onClickDelete = {
                SodaDialog(
                    activity = this@UserProfileFantalkAllViewActivity,
                    layoutInflater = layoutInflater,
                    title = "응원글 삭제",
                    desc = "삭제하시겠습니까?",
                    confirmButtonTitle = "삭제",
                    confirmButtonClick = {
                        cheersAdapter.items.clear()
                        viewModel.modifyCheers(
                            cheersId = it,
                            creatorId = userId,
                            isActive = false
                        )
                    },
                    cancelButtonTitle = "취소",
                    cancelButtonClick = {}
                ).show(screenWidth)
            },
            onClickProfile = {
                MemberProfileDialog(
                    activity = this@UserProfileFantalkAllViewActivity,
                    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
        rvCheers.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 = cheersAdapter.itemCount - 1

                if (itemTotalCount > 0 && lastVisiblePosition == itemTotalCount) {
                    viewModel.getCheersList(userId)
                }
            }
        })
    }

    private fun hideKeyboard(onAfterExecute: () -> Unit) {
        handler.postDelayed({
            imm.hideSoftInputFromWindow(
                window.decorView.applicationWindowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
            onAfterExecute()
        }, 100)
    }

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

    @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.cheersLiveData.observe(this) {
            binding.etCheer.setText("")

            binding.tvCheersCount.text = it.totalCount.toString()
            binding.tvCheersCount.requestLayout()
            cheersAdapter.items.addAll(it.cheers)
            cheersAdapter.notifyDataSetChanged()

            if (cheersAdapter.itemCount <= 0) {
                binding.rvCheers.visibility = View.GONE
                binding.tvNoCheers.visibility = View.VISIBLE
            } else {
                binding.rvCheers.visibility = View.VISIBLE
                binding.tvNoCheers.visibility = View.GONE
            }

            binding.rvCheers.requestLayout()
        }
    }
}
