package melody.offline.music.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
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.activity.MoLikedSongsActivity
import melody.offline.music.activity.MoOfflineSongsActivity
import melody.offline.music.activity.MoPlaylistSongsActivity
import melody.offline.music.activity.SettingsActivity
import melody.offline.music.adapter.LikedSongsAdapter
import melody.offline.music.adapter.NewPlayListAdapter
import melody.offline.music.ads.AdPlacement
import melody.offline.music.ads.LolAdWrapper
import melody.offline.music.bean.FavoriteBean
import melody.offline.music.bean.Playlist
import melody.offline.music.databinding.FragmentMoMeBinding
import melody.offline.music.util.AnalysisUtil

class MoMeFragment : MoBaseFragment<FragmentMoMeBinding>(), NewPlayListAdapter.OnItemClickListener {

    private val requests: Channel<Request> = Channel(Channel.UNLIMITED)
    private var adapter: NewPlayListAdapter? = null
    private var playlist: MutableList<Playlist> = mutableListOf()

    sealed class Request {
        data class AddPlaylist(val text: String) : Request()
    }

    override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentMoMeBinding
        get() = FragmentMoMeBinding::inflate

    override suspend fun onViewCreated() {
        LolAdWrapper.shared.loadAdIfNotCached(requireActivity(), AdPlacement.INST_ME_PAGE_LIST)
        initView()
        initAdapter()
        onReceive()
    }

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

    private suspend fun onReceive() {
        while (isActive) {
            select<Unit> {
                requests.onReceive {
                    when (it) {
                        is Request.AddPlaylist -> {
                            val playlist = App.appPlaylistDBManager.getPlaylistByTitle(it.text)
                            if (playlist != null) {
                                Toast.makeText(
                                    requireActivity(),
                                    getString(R.string.new_playlist_duplicate_name_hint),
                                    Toast.LENGTH_LONG
                                ).show()
                            } else {
                                val newPlaylist = Playlist(title = it.text)
                                App.appPlaylistDBManager.insertOrUpdatePlaylist(newPlaylist)
                                if (bottomSheetDialog != null) {
                                    bottomSheetDialog?.dismiss()
                                }
                                getPlaylistData()
                            }
                        }
                    }
                }

                events.onReceive {
                    when (it) {
                        Event.FragmentOnResume -> {
                            fragmentOnResume()
                        }
                    }
                }
            }
        }
    }

    private fun initView() {
        binding.settingBtn.setOnClickListener {
            val intent = Intent(requireActivity(), SettingsActivity::class.java)
            intent.putExtra(SettingsActivity.FROM_TO_SETTING, MoMeFragment::class.java)
            startActivity(intent)
        }
        binding.likedSongsBtn.setOnClickListener {
            val count = binding.likedSongsTv.text.toString().trim().toInt()
            if (count > 0) {
                val intent = Intent(context, MoLikedSongsActivity::class.java)
                startActivity(intent)
            } else {
                Toast.makeText(
                    activity, getString(R.string.liked_songs_no_data_prompt), Toast.LENGTH_LONG
                ).show()
            }
        }
        binding.offlineSongsBtn.setOnClickListener {
            val count = binding.offlineSongsTv.text.toString().trim().toInt()
            if (count > 0) {
                val intent = Intent(context, MoOfflineSongsActivity::class.java)
                startActivity(intent)
            } else {
                Toast.makeText(
                    activity, getString(R.string.offline_songs_no_data_prompt), Toast.LENGTH_LONG
                ).show()
            }
        }
        binding.newPlayListBtn.setOnClickListener {
            showBottomDialog()
        }
    }

    private suspend fun fragmentOnResume() {
        //过滤只有size大于0的才计数
        val offlineBeans = App.appOfflineDBManager.getAllOfflineBeans()
        val count = offlineBeans.count { it.bytesDownloaded?.let { bytes -> bytes > 0 } == true }
        binding.offlineSongsTv.text = "$count"

        //过滤只有为true的才计数
        val favoriteBeans = App.appFavoriteDBManager.getAllFavoriteBeans()
        val favorites = favoriteBeans.count { it.isFavorite }
        binding.likedSongsTv.text = "$favorites"

        getPlaylistData()
    }

    override fun onResume() {
        super.onResume()
        initImmersionBar()
        AnalysisUtil.logEvent(AnalysisUtil.ME_B_PV)
        LolAdWrapper.shared.loadAdShowNativeAd(
            requireActivity(),
            AdPlacement.NATIVE_ME_PAGE_LIST,
            binding.frameAd,
            R.layout.ad_layout_admob_banner,
            R.layout.ad_layout_max_banner
        )
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initImmersionBar()
        }
    }

    private fun initAdapter() {
        adapter = NewPlayListAdapter(requireActivity(), playlist)
        adapter?.setOnItemClickListener(this)
        binding.newPlayListRv.layoutManager =
            LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
        binding.newPlayListRv.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private suspend fun getPlaylistData() {
        playlist.clear()
        playlist.addAll(App.appPlaylistDBManager.getAllPlaylists())
        adapter?.notifyDataSetChanged()
    }

    override fun onItemClick(position: Int) {
        val intent = Intent(requireActivity(), MoPlaylistSongsActivity::class.java)
        intent.putExtra(MoPlaylistSongsActivity.PLAYLIST_ID, playlist[position].id)
        intent.putExtra(MoPlaylistSongsActivity.PLAYLIST_TITLE, playlist[position].title)
        startActivity(intent)
    }

    private var bottomSheetDialog: BottomSheetDialog? = null
    private fun showBottomDialog() {
        bottomSheetDialog = BottomSheetDialog(requireActivity())
        val view = layoutInflater.inflate(R.layout.new_playlist_layout, null)
        bottomSheetDialog?.setContentView(view)
        val edit = view.findViewById<EditText>(R.id.playlistEt)
        val confirmBtn = view.findViewById<TextView>(R.id.confirmBtn)
        confirmBtn.setOnClickListener {
            val text = edit.text.toString().trim()
            if (text.isNotEmpty()) {
                requests.trySend(Request.AddPlaylist(text))
            }
        }
        // 设置对话框背景为透明以显示圆角
        bottomSheetDialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
        bottomSheetDialog?.window?.navigationBarColor =
            ContextCompat.getColor(requireActivity(), R.color.main_bg_color)
        bottomSheetDialog?.show()
    }

}