package melody.offline.music.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.annotation.OptIn
import androidx.appcompat.app.AlertDialog
import androidx.media3.common.util.UnstableApi
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import melody.offline.music.App
import melody.offline.music.R
import melody.offline.music.adapter.PlaylistSongsAdapter
import melody.offline.music.ads.AdPlacement
import melody.offline.music.ads.LolAdWrapper
import melody.offline.music.bean.PlaylistItem
import melody.offline.music.databinding.ActivityPlaylistSongsBinding

@OptIn(UnstableApi::class)
class MoPlaylistSongsActivity : MoBaseActivity() {
    companion object {
        const val PLAYLIST_ID = "playlist_id"
        const val PLAYLIST_TITLE = "playlist_title"
    }

    private val requests: Channel<Request> = Channel(Channel.UNLIMITED)

    sealed class Request {
        data object TryAgain : Request()
    }

    private lateinit var binding: ActivityPlaylistSongsBinding
    private var adapter: PlaylistSongsAdapter? = null
    private var playlistItems: MutableList<PlaylistItem> = mutableListOf()
    private var currentPosition = -1
    private var playlistId = -1
    private var playlistTitle = ""

    override suspend fun main() {
        binding = ActivityPlaylistSongsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        playlistId = intent.getIntExtra(PLAYLIST_ID, -1)
        playlistTitle = intent.getStringExtra(PLAYLIST_TITLE) ?: ""
        LolAdWrapper.shared.showAdTiming(this, AdPlacement.INST_ME_PAGE_LIST)
        initImmersionBar()
        initView()
        initAdapter()
        LolAdWrapper.shared.loadAdIfNotCached(this, AdPlacement.INST_ME_PAGE_LIST)
        initData()
        onReceive()
    }

    private fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(false)
            statusBarView(binding.view)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private suspend fun onReceive() {
        while (isActive) {
            select<Unit> {
                requests.onReceive {
                    when (it) {
                        Request.TryAgain -> {
                            initData()
                        }
                    }
                }
                events.onReceive {
                    when (it) {
                        Event.ActivityOnResume -> {
                            activityOnResume()
                        }

                        Event.AutomaticallySwitchSongs -> {
                            if (adapter != null) {
                                adapter?.notifyDataSetChanged()
                            }
                        }

                        else -> {}
                    }
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun activityOnResume() {
        addMusicPlayerViewToLayout(binding.playMusicLayout)

        if (adapter != null) {
            adapter?.notifyDataSetChanged()
        }

        try {
            LolAdWrapper.shared.loadAdShowNativeAd(
                this,
                AdPlacement.NATIVE_ME_PAGE_LIST,
                binding.frameAd,
                R.layout.ad_layout_admob_banner,
                R.layout.ad_layout_max_banner
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun initView() {
        binding.titleText.text = playlistTitle
        binding.layoutInfo.setOnClickListener { }
        binding.backBtn.setOnClickListener {
            finish()
        }
        binding.tryAgainBtn.setOnClickListener {
            requests.trySend(Request.TryAgain)
        }
        binding.bottomCloseBtn.setOnClickListener {
            hideBottomLayout()
        }
        binding.bottomBlankLayout.setOnClickListener {
            hideBottomLayout()
        }
        binding.moreDownloadBtn.setOnClickListener {
            if (currentPosition >= 0) {

            }
        }
        binding.moreAddPlaylistBtn.setOnClickListener {
            if (currentPosition >= 0) {
            }
        }
        binding.favoritesBtn.setOnClickListener {
            if (currentPosition >= 0) {
            }
        }
    }

    private fun initAdapter() {
        adapter = PlaylistSongsAdapter(this, playlistItems)
        adapter?.setOnMoreClickListener(object : PlaylistSongsAdapter.OnMoreClickListener {
            override fun onMoreClick(position: Int) {
                currentPosition = position
                toggleBottomLayout(position)
            }
        })
        binding.rv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rv.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private suspend fun initData() {
        showLoadingUi()
        playlistItems.clear()
        playlistItems.addAll(App.appPlaylistDBManager.getPlaylistItems(playlistId))
        if (playlistItems.size > 0) {
            showDataUi()
        } else {
            showNoContentUi()
        }
        if (adapter != null) {
            adapter?.notifyDataSetChanged()
        }
    }

    private fun showRemoveDownloadDialogHint(id: String) {
        val inflater = LayoutInflater.from(this)
        val dialogView = inflater.inflate(R.layout.dialog_hint, null)
        val okBtn = dialogView.findViewById<TextView>(R.id.dialog_ok_btn)
        val cancelBtn = dialogView.findViewById<TextView>(R.id.dialog_cancel_btn)
        val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
        val dialog = dialogBuilder.create()
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
        okBtn.setOnClickListener {
            dialog.dismiss()
        }
        cancelBtn.setOnClickListener {
            dialog.dismiss()
        }
    }

    private fun updateFavoriteUi(b: Boolean) {
        if (b) {
            binding.favoritesImg.setImageResource(R.drawable.favorited_icon)
        } else {
            binding.favoritesImg.setImageResource(R.drawable.not_favorited_icon)
        }
    }

    private fun toggleBottomLayout(position: Int) {
        if (binding.bottomLayout.visibility == View.VISIBLE) {
            hideBottomLayout()
        } else {
            showBottomLayout(position)
        }
    }

    private fun showBottomLayout(position: Int) {
        val slideUpAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_up)
        binding.bottomLayout.startAnimation(slideUpAnimation)
        binding.bottomLayout.visibility = View.VISIBLE

        val bean = playlistItems[position]
        Glide.with(this).load(bean.thumbnail).into(binding.songImg)
        binding.title.text = bean.title
        if (bean.name.isEmpty()) {
            binding.name.visibility = View.GONE
        } else {
            binding.name.visibility = View.VISIBLE
            binding.name.text = bean.name
        }
    }

    private fun hideBottomLayout() {
        val slideDownAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_down)
        binding.bottomLayout.startAnimation(slideDownAnimation)
        binding.bottomLayout.visibility = View.GONE
    }

    private fun showDataUi() {
        binding.loadingLayout.visibility = View.GONE
        binding.noContentLayout.visibility = View.GONE
    }

    private fun showLoadingUi() {
        binding.loadingLayout.visibility = View.VISIBLE
        binding.noContentLayout.visibility = View.GONE
    }

    private fun showNoContentUi() {
        binding.loadingLayout.visibility = View.GONE
        binding.noContentLayout.visibility = View.VISIBLE
    }
}