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

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import kr.co.vividnext.sodalive.audio_content.playlist.modify.AudioContentPlaylistModifyActivity
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.ActivityAudioContentPlaylistDetailBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentPlaylistDetailActivity : BaseActivity<ActivityAudioContentPlaylistDetailBinding>(
    ActivityAudioContentPlaylistDetailBinding::inflate
) {

    private val viewModel: AudioContentPlaylistDetailViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: AudioContentPlaylistDetailAdapter

    private var playlistId: Long = 0

    private val modifyPlaylistResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            viewModel.getPlaylistDetail(playlistId)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        playlistId = intent.getLongExtra(Constants.EXTRA_AUDIO_CONTENT_PLAYLIST_ID, 0)
        super.onCreate(savedInstanceState)

        if (playlistId <= 0) {
            showToast("잘못된 요청입니다.")
            finish()
        }

        bindData()
        viewModel.getPlaylistDetail(playlistId)
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        adapter = AudioContentPlaylistDetailAdapter()

        val recyclerView = binding.rvPlaylistDetail
        recyclerView.setHasFixedSize(true)
        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 = 0
                outRect.right = 0

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

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

                    else -> {
                        outRect.top = 6.7f.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }
                }
            }
        })
        recyclerView.adapter = adapter

        binding.llPlay.setOnClickListener { }
        binding.llShuffle.setOnClickListener { }
        binding.tvBack.setOnClickListener { finish() }
        binding.ivEdit.setOnClickListener {
            modifyPlaylistResult.launch(
                Intent(
                    applicationContext,
                    AudioContentPlaylistModifyActivity::class.java
                ).apply {
                    putExtra(
                        Constants.EXTRA_AUDIO_CONTENT_PLAYLIST_ID,
                        playlistId
                    )
                }
            )
        }
        binding.ivMore.setOnClickListener {
            val notifyFragment = AudioContentPlaylistDetailNotifyFragment {
                SodaDialog(
                    activity = this@AudioContentPlaylistDetailActivity,
                    layoutInflater = layoutInflater,
                    title = "재생 목록 삭제",
                    desc = "'${binding.tvTitle.text}'을 삭제하시겠습니까?",
                    confirmButtonTitle = "삭제",
                    confirmButtonClick = {
                        viewModel.deletePlaylist(playlistId = playlistId) {
                            setResult(RESULT_OK)
                            finish()
                        }
                    },
                    cancelButtonTitle = "취소",
                    cancelButtonClick = {}
                ).show(screenWidth)
            }

            if (notifyFragment.isAdded) return@setOnClickListener
            notifyFragment.show(supportFragmentManager, notifyFragment.tag)
        }
    }

    @SuppressLint("SetTextI18n")
    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.detailResponseLiveData.observe(this) {
            binding.tvDesc.text = it.desc
            binding.tvTitle.text = it.title
            binding.tvContentCount.text = " ${it.contentCount}개"
            binding.tvCreateDate.text = "만든 날짜 ${it.createdDate} "
            adapter.updateItems(it.contentList)
            updateCoverImageLayout(imageUrlList = it.playlistCoverImageList)
        }
    }

    private fun updateCoverImageLayout(imageUrlList: List<String>) {
        val imageViews = listOf(
            binding.ivCover1,
            binding.ivCover2,
            binding.ivCover3,
            binding.ivCover4,
            binding.ivCover5,
            binding.ivCover6
        )

        imageViews.forEach { it.visibility = View.GONE }

        when (imageUrlList.size) {
            1, 2 -> {
                setImage(imageViews[0], imageUrlList[0])
            }

            3 -> {
                setImage(imageViews[1], imageUrlList[0])
                setImage(imageViews[2], imageUrlList[1])
                setImage(imageViews[3], imageUrlList[2])
            }

            4 -> {
                setImage(imageViews[1], imageUrlList[0])
                setImage(imageViews[2], imageUrlList[1])
                setImage(imageViews[4], imageUrlList[2])
                setImage(imageViews[5], imageUrlList[3])
            }
        }
    }

    private fun setImage(imageView: ImageView, imageUrl: String) {
        imageView.apply {
            visibility = View.VISIBLE
            this.load(imageUrl)
        }
    }
}
