package kr.co.vividnext.sodalive.explorer.profile.creator_community.all.player

import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.widget.Toast
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kr.co.vividnext.sodalive.audio_content.AudioContentPlayService
import java.io.IOException

@Keep
data class CreatorCommunityContentItem(
    @SerializedName("contentId") val contentId: Long,
    @SerializedName("url") val url: String
)

class CreatorCommunityMediaPlayerManager(
    private val context: Context,
    private val updateUI: () -> Unit
) {
    private var mediaPlayer: MediaPlayer? = null
    private var currentPlayingContentId: Long? = null
    private var isPaused: Boolean = false

    fun pauseContent() {
        mediaPlayer?.pause()
        isPaused = true
        updateUI()
    }

    private fun resumeContent() {
        pauseAudioContentService()
        mediaPlayer?.start()
        isPaused = false
        updateUI()
    }

    fun stopContent() {
        mediaPlayer?.let {
            it.stop()
            it.release()
            mediaPlayer = null
        }
        currentPlayingContentId = null
        isPaused = false
        updateUI()
    }

    fun toggleContent(creatorCommunityContentItem: CreatorCommunityContentItem) {
        if (currentPlayingContentId == creatorCommunityContentItem.contentId) {
            if (mediaPlayer?.isPlaying == true) {
                pauseContent()
            } else {
                resumeContent()
            }
        } else {
            playContent(creatorCommunityContentItem)
        }
    }

    fun isPlayingContent(contentId: Long): Boolean {
        return currentPlayingContentId == contentId && mediaPlayer?.isPlaying == true
    }

    private fun playContent(creatorCommunityContentItem: CreatorCommunityContentItem) {
        pauseAudioContentService()

        if (currentPlayingContentId == creatorCommunityContentItem.contentId && isPaused) {
            resumeContent()
            return
        }

        stopContent()

        mediaPlayer = MediaPlayer().apply {
            setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build()
            )

            try {
                setDataSource(context, Uri.parse(creatorCommunityContentItem.url))
                prepareAsync() // 비동기적으로 준비
                setOnPreparedListener {
                    start()
                    updateUI() // 준비 완료 후 UI 업데이트
                }
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(context, "콘텐츠를 재생하지 못했습니다.\n다시 시도해 주세요", Toast.LENGTH_SHORT).show()
            }

            setOnCompletionListener {
                currentPlayingContentId = null
                updateUI() // 재생 완료 후 UI 업데이트
            }
        }

        currentPlayingContentId = creatorCommunityContentItem.contentId
        isPaused = false
        updateUI()
    }

    private fun pauseAudioContentService() {
        context.startService(
            Intent(
                context,
                AudioContentPlayService::class.java
            ).apply {
                action = AudioContentPlayService.MusicAction.PAUSE.name
            }
        )
    }
}
