package kr.co.vividnext.sodalive.audio_content.playlist

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.audio_content.playlist.create.AudioContentPlaylistCreateActivity
import kr.co.vividnext.sodalive.audio_content.playlist.detail.AudioContentPlaylistDetailActivity
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.FragmentAudioContentPlaylistListBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentPlaylistListFragment : BaseFragment<FragmentAudioContentPlaylistListBinding>(
    FragmentAudioContentPlaylistListBinding::inflate
) {

    private val viewModel: AudioContentPlaylistListViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AudioContentPlaylistListAdapter

    private val createOrUpdatePlaylistResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            viewModel.getPlaylistList()
        }
    }

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

        setupView()
        bindData()
        viewModel.getPlaylistList()
    }

    private fun setupView() {
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)
        adapter = AudioContentPlaylistListAdapter { playlistId ->
            createOrUpdatePlaylistResult.launch(
                Intent(requireContext(), AudioContentPlaylistDetailActivity::class.java).apply {
                    putExtra(
                        Constants.EXTRA_AUDIO_CONTENT_PLAYLIST_ID,
                        playlistId
                    )
                }
            )
        }

        val recyclerView = binding.rvPlaylistList
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(
            activity,
            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 = 0
                outRect.right = 0

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

                    adapter.itemCount - 1 -> {
                        outRect.top = 5f.dpToPx().toInt()
                        outRect.bottom = 0
                    }

                    else -> {
                        outRect.top = 5f.dpToPx().toInt()
                        outRect.bottom = 5f.dpToPx().toInt()
                    }
                }
            }
        })

        recyclerView.adapter = adapter

        binding.tvCreatePlaylist.setOnClickListener {
            createOrUpdatePlaylistResult.launch(
                Intent(
                    requireContext(),
                    AudioContentPlaylistCreateActivity::class.java
                )
            )
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindData() {
        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { showToast(it) }
        }

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

        viewModel.playlistLiveData.observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                binding.tvTotalCount.visibility = View.GONE
                binding.rvPlaylistList.visibility = View.GONE
                binding.llNoPlaylist.visibility = View.VISIBLE
            } else {
                binding.llNoPlaylist.visibility = View.GONE
                binding.tvTotalCount.visibility = View.VISIBLE
                binding.rvPlaylistList.visibility = View.VISIBLE

                adapter.updateItems(it)
            }
        }
    }
}
