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

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.base.BaseActivity
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityUserFollowerListBinding
import kr.co.vividnext.sodalive.explorer.profile.CreatorFollowNotifyFragment
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat
import org.koin.android.ext.android.inject

class UserFollowerListActivity : BaseActivity<ActivityUserFollowerListBinding>(
    ActivityUserFollowerListBinding::inflate
) {

    private val viewModel: UserFollowerListViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: UserFollowerListAdapter

    private var userId: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        userId = intent.getLongExtra(Constants.EXTRA_USER_ID, 0)

        if (userId <= 0) {
            Toast.makeText(
                applicationContext,
                "잘못된 요청입니다.\n다시 시도해 주세요.",
                Toast.LENGTH_LONG
            ).show()

            finish()
        }

        super.onCreate(savedInstanceState)

        bindData()
        viewModel.getFollowerList()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "팔로워 리스트"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        adapter = UserFollowerListAdapter(
            onClickFollow = { creatorId, isFollow ->
                if (isFollow) {
                    val notifyFragment = CreatorFollowNotifyFragment(
                        onClickNotifyAll = {
                            viewModel.follow(creatorId, follow = true, notify = true)
                        },
                        onClickNotifyNone = {
                            viewModel.follow(creatorId, follow = true, notify = false)
                        },
                        onClickUnFollow = {
                            viewModel.follow(creatorId, follow = false, notify = false)
                        }
                    )

                    if (notifyFragment.isAdded) return@UserFollowerListAdapter
                    notifyFragment.show(supportFragmentManager, notifyFragment.tag)
                } else {
                    viewModel.follow(creatorId)
                }
            }
        )

        binding.rvFollowerList.layoutManager = LinearLayoutManager(
            applicationContext,
            LinearLayoutManager.VERTICAL,
            false
        )

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

                val layoutManager = recyclerView.layoutManager as? LinearLayoutManager
                if (
                    layoutManager != null &&
                    layoutManager.findLastCompletelyVisibleItemPosition() == adapter.itemCount - 1
                ) {
                    viewModel.getFollowerList()
                }
            }
        })

        binding.rvFollowerList.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)

                outRect.left = 20f.dpToPx().toInt()
                outRect.right = 20f.dpToPx().toInt()
            }
        })

        binding.rvFollowerList.adapter = adapter
    }

    private fun bindData() {
        viewModel.userId = userId
        viewModel.followerListItemsLiveData.observe(this) {
            if (viewModel.page == 2) adapter.clear()
            adapter.addAll(it)
        }

        viewModel.totalCountLiveData.observe(this) {
            binding.tvCount.text = it.moneyFormat()
        }

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