package kr.co.vividnext.sodalive.audio_content.order

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.FragmentAudioContentOrderListBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentOrderListFragment : BaseFragment<FragmentAudioContentOrderListBinding>(
    FragmentAudioContentOrderListBinding::inflate
) {
    private val viewModel: AudioContentOrderListViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AudioContentOrderListAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupView()
        bindData()
        viewModel.getAudioContentOrderList { requireActivity().finish() }
    }

    fun setupView() {
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)

        adapter = AudioContentOrderListAdapter {
            startActivity(
                Intent(requireContext(), AudioContentDetailActivity::class.java)
                    .apply { putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it) }
            )
        }

        binding.rvOrderList.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.VERTICAL,
            false
        )

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

                outRect.left = 13.3f.dpToPx().toInt()
                outRect.right = 13.3f.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()
                    }
                }
            }
        })

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

                val lastVisibleItemPosition = (recyclerView.layoutManager as LinearLayoutManager?)!!
                    .findLastCompletelyVisibleItemPosition()
                val itemTotalCount = recyclerView.adapter!!.itemCount - 1

                // 스크롤이 끝에 도달했는지 확인
                if (!recyclerView.canScrollVertically(1) &&
                    lastVisibleItemPosition == itemTotalCount
                ) {
                    viewModel.getAudioContentOrderList {}
                }
            }
        })

        binding.rvOrderList.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { showToast(it) }
        }

        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth, "")
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.orderList.observe(viewLifecycleOwner) {
            if (viewModel.page == 2) {
                adapter.items.clear()
            }

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

        viewModel.totalCount.observe(viewLifecycleOwner) {
            binding.tvTotalCount.text = "$it"
        }
    }
}
