package melody.offline.music.view

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.annotation.OptIn
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.offline.Download
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import melody.offline.music.R
import melody.offline.music.bean.PlaylistItem
import melody.offline.music.service.ViewModelMain
import melody.offline.music.util.AnalysisUtil
import melody.offline.music.util.DownloadUtil
import melody.offline.music.util.LogTag
import org.json.JSONObject

@OptIn(UnstableApi::class)
class ListMoreBottomSheetDialog(
    private val context: Activity,
    private val playlistItem: PlaylistItem,
    private val lifecycleOwner: LifecycleOwner,
    private val updateAdapterListener: UpdateAdapterListener,
    private val isPlayList: Boolean? = null
) : BottomSheetDialog(context) {
    private var bottomDialogBottomLayout: LinearLayout? = null
    private var bottomDialogBottomCloseBtn: LinearLayout? = null
    private var bottomDialogSongImg: ImageView? = null
    private var bottomDialogTitle: TextView? = null
    private var bottomDialogName: TextView? = null
    private var bottomDialogFavoritesBtn: LinearLayout? = null
    private var bottomDialogFavoritesImg: ImageView? = null
    private var bottomDialogMoreDownloadBtn: LinearLayout? = null
    private var bottomDialogDownloadImg: ImageView? = null
    private var bottomDialogDownloadLoading: ProgressBar? = null
    private var bottomDialogDownloadTv: TextView? = null
    private var bottomDialogMoreAddPlaylistBtn: LinearLayout? = null
    private var bottomDialogAddPlaylistTv: TextView? = null
    private lateinit var observer: Observer<Map<String, Download>>

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.list_more_layout)
        initDownloadFlow()
        window?.setBackgroundDrawableResource(android.R.color.transparent)
        window?.navigationBarColor = ContextCompat.getColor(context, R.color.main_bg_color)
        initView()
        initInfoUi()
        initClick()
    }

    private fun initView() {
        bottomDialogBottomLayout = findViewById(R.id.bottomDialogBottomLayout)
        bottomDialogBottomCloseBtn = findViewById(R.id.bottomDialogBottomCloseBtn)
        bottomDialogSongImg = findViewById(R.id.bottomDialogSongImg)
        bottomDialogTitle = findViewById(R.id.bottomDialogTitle)
        bottomDialogName = findViewById(R.id.bottomDialogName)
        bottomDialogFavoritesBtn = findViewById(R.id.bottomDialogFavoritesBtn)
        bottomDialogFavoritesImg = findViewById(R.id.bottomDialogFavoritesImg)
        bottomDialogMoreDownloadBtn = findViewById(R.id.bottomDialogMoreDownloadBtn)
        bottomDialogDownloadImg = findViewById(R.id.bottomDialogDownloadImg)
        bottomDialogDownloadLoading = findViewById(R.id.bottomDialogDownloadLoading)
        bottomDialogDownloadTv = findViewById(R.id.bottomDialogDownloadTv)
        bottomDialogMoreAddPlaylistBtn = findViewById(R.id.bottomDialogMoreAddPlaylistBtn)
        bottomDialogAddPlaylistTv = findViewById(R.id.bottomDialogAddPlaylistTv)
    }

    private fun initInfoUi() {
        if (isPlayList == true) {//如果是playlist点击进入则为remove
            bottomDialogAddPlaylistTv?.text = context.getString(R.string.remove_from_playlist)
        } else {
            bottomDialogAddPlaylistTv?.text = context.getString(R.string.add_to_playlist)
        }

        val bean = playlistItem
        Glide.with(context).load(bean.thumbnail).into(bottomDialogSongImg!!)
        bottomDialogTitle?.text = bean.title
        if (bean.name.isEmpty()) {
            bottomDialogName?.visibility = View.GONE
        } else {
            bottomDialogName?.visibility = View.VISIBLE
            bottomDialogName?.text = bean.name
        }
        LogTag.LogD(LogTag.VO_TEST_ONLY, "more dialog ->$bean")
        updateFavoriteUi(bean.isFavorite)

        //获取当前ID的下载记录
        val currentDownload = DownloadUtil.getCurrentIdDownload(bean.videoId)
        if (currentDownload != null) {
            LogTag.LogD(LogTag.VO_TEST_ONLY, "000->${currentDownload.state}")
            //是否下载过资源，下载过资源就不走download的ui更新，因为 它肯定状态为3
            if (DownloadUtil.downloadResourceExist(bean.videoId)) {
                updateDownloadBtnUi(bean.isOffline)

                LogTag.LogD(LogTag.VO_TEST_ONLY, "11更新 ui")
            } else {
                updateDownloadUI(currentDownload)

                LogTag.LogD(LogTag.VO_TEST_ONLY, "22更新 ui")
            }
        } else {
            updateDownloadBtnUi(bean.isOffline)
            LogTag.LogD(LogTag.VO_TEST_ONLY, "33 更新btn ui")
        }
    }

    private fun initClick() {
        bottomDialogBottomCloseBtn?.setOnClickListener {
            dismiss()
        }
        bottomDialogFavoritesBtn?.setOnClickListener {
            if (listenerMoreView != null) {
                listenerMoreView?.onFavoritesClicked(playlistItem)
            }
        }
        bottomDialogMoreDownloadBtn?.setOnClickListener {
            if (listenerMoreView != null) {
                listenerMoreView?.onDownloadClicked(playlistItem)
            }
        }
        bottomDialogMoreAddPlaylistBtn?.setOnClickListener {
            if (listenerMoreView != null) {
                listenerMoreView?.onAddToPlaylistClicked(playlistItem)
            }
        }
    }

    fun updateFavoriteUi(b: Boolean) {
        if (b) {
            bottomDialogFavoritesImg?.setImageResource(R.drawable.favorited_icon)
        } else {
            bottomDialogFavoritesImg?.setImageResource(R.drawable.not_favorited_icon)
        }
    }

    fun updateDownloadBtnUi(b: Boolean) {
        LogTag.LogD(LogTag.VO_TEST_ONLY, "more dialog updateDownloadBtnUi ->$b")
        if (b) {
            bottomDialogDownloadLoading?.visibility = View.GONE
            bottomDialogDownloadImg?.visibility = View.VISIBLE
            bottomDialogDownloadImg?.setImageResource(R.drawable.more_downloaded_icon)
            bottomDialogDownloadTv?.text = context.getString(R.string.download_remove_offline)
        } else {
            bottomDialogDownloadLoading?.visibility = View.GONE
            bottomDialogDownloadImg?.visibility = View.VISIBLE
            bottomDialogDownloadImg?.setImageResource(R.drawable.more_download_icon)
            bottomDialogDownloadTv?.text = context.getString(R.string.download_save_offline)
        }
    }

    private fun initDownloadFlow() {
        observer = Observer { downloads ->
            val id = playlistItem.videoId
            val currentScreenDownloads = downloads[id]
            if (currentScreenDownloads != null) {
                LogTag.LogD(LogTag.VO_TEST_ONLY, "more dialog initDownloadFlow")
                updateDownloadUI(currentScreenDownloads)
            }
        }
        ViewModelMain.modelDownloadsFlow.observe(lifecycleOwner, observer)
    }

    override fun dismiss() {
        super.dismiss()
        ViewModelMain.modelDownloadsFlow.removeObserver(observer)
    }

    private fun updateDownloadUI(download: Download) {
        LogTag.LogD(LogTag.VO_TEST_ONLY, "more dialog download->${download.state}")
        when (download.state) {
            Download.STATE_DOWNLOADING -> {
                bottomDialogDownloadLoading?.visibility = View.VISIBLE
                bottomDialogDownloadImg?.setImageResource(R.drawable.more_download_icon)
                bottomDialogDownloadImg?.visibility = View.GONE

                bottomDialogDownloadTv?.text = context.getString(R.string.download_saving)

                bottomDialogMoreDownloadBtn?.isClickable = false
                bottomDialogMoreDownloadBtn?.isEnabled = false
            }

            Download.STATE_COMPLETED -> {
                updateAdapterListener.onUpdateAdapterListener(download, playlistItem)
                bottomDialogDownloadLoading?.visibility = View.GONE
                bottomDialogDownloadImg?.setImageResource(R.drawable.more_downloaded_icon)
                bottomDialogDownloadImg?.visibility = View.VISIBLE

                bottomDialogDownloadTv?.text = context.getString(R.string.download_remove_offline)

                bottomDialogMoreDownloadBtn?.isClickable = true
                bottomDialogMoreDownloadBtn?.isEnabled = true

                val jsonObject = JSONObject()
                jsonObject.put(
                    "download_id", download.request.id
                )
                val songMap = mutableMapOf(
                    Pair(
                        AnalysisUtil.PARAM_VALUE, jsonObject.toString()
                    )
                )
                AnalysisUtil.logEvent(AnalysisUtil.PLAYER_B_DOWNLOAD_SUCCESS_ACTION, songMap)
            }

            Download.STATE_FAILED -> {
                bottomDialogDownloadLoading?.visibility = View.GONE
                bottomDialogDownloadImg?.setImageResource(R.drawable.error)
                bottomDialogDownloadImg?.visibility = View.VISIBLE

                bottomDialogDownloadTv?.text = context.getString(R.string.download_save_offline)

                bottomDialogMoreDownloadBtn?.isClickable = true
                bottomDialogMoreDownloadBtn?.isEnabled = true
            }

            else -> {
                bottomDialogDownloadLoading?.visibility = View.GONE
                bottomDialogDownloadImg?.setImageResource(R.drawable.more_download_icon)
                bottomDialogDownloadImg?.visibility = View.VISIBLE

                bottomDialogDownloadTv?.text = context.getString(R.string.download_save_offline)

                bottomDialogMoreDownloadBtn?.isClickable = true
                bottomDialogMoreDownloadBtn?.isEnabled = true
            }
        }
    }

    // 定义一个接口用于回调事件
    interface ListMoreViewListener {
        fun onFavoritesClicked(playlistItem: PlaylistItem) {}
        fun onDownloadClicked(playlistItem: PlaylistItem) {}
        fun onAddToPlaylistClicked(playlistItem: PlaylistItem) {}
    }

    private var listenerMoreView: ListMoreViewListener? = null

    // 设置监听器
    fun setListMoreViewListener(listener: ListMoreViewListener) {
        this.listenerMoreView = listener
    }

    interface UpdateAdapterListener {
        fun onUpdateAdapterListener(download: Download, playlistItem: PlaylistItem)
    }
}
