package com.example.lexilearn

import android.content.Context
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.UserDataModel
import com.example.lexilearn.data.repository.UserRepository
import com.example.lexilearn.ui.theme.LexiLearnTheme
import com.example.lexilearn.ui.views.pDetailMaterial.DetailMaterialScreen
import com.example.lexilearn.ui.views.pHome.HomeScreen
import com.example.lexilearn.ui.views.pLearAlphabet.LearnAlphabetScreen
import com.example.lexilearn.ui.views.pNavMaterial.NavMaterialScreen
import com.example.lexilearn.ui.views.pLearnNumber.LearnNumberScreen
import com.example.lexilearn.ui.views.pLogin.LoginScreen
import com.example.lexilearn.ui.views.pQuiz.QuizScreen
import com.example.lexilearn.ui.views.pQuiz.pRead.ReadScreen
import com.example.lexilearn.ui.views.pQuiz.pSpell.SpellScreen
import com.example.lexilearn.ui.views.pQuiz.pWrite.WriteScreen
import com.example.lexilearn.ui.views.pRegister.RegisterScreen
import com.example.lexilearn.ui.views.pResultScreening.ResultScreeningScreen
import com.example.lexilearn.ui.views.pScreening.ScreeningScreen
import com.example.lexilearn.ui.views.pSplashcreen.SplashScreen
class BackgroundMusicPlayer(private val context: Context) {
    private var mediaPlayer: MediaPlayer? = null

    fun play() {
        // Stop existing player if any
        stop()

        // Create new media player
        mediaPlayer = MediaPlayer.create(context, R.raw.music_background).apply {
            isLooping = true
            setVolume(0.2f, 0.2f) // Set volume to 30%
            start()
        }
    }

    fun pause() {
        mediaPlayer?.pause()
    }

    fun resume() {
        mediaPlayer?.start()
    }

    fun stop() {
        mediaPlayer?.let {
            if (it.isPlaying) {
                it.stop()
            }
            it.release()
        }
        mediaPlayer = null
    }
}

@Composable
fun BackgroundMusicHandler() {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val musicPlayer = remember { BackgroundMusicPlayer(context) }

    // Observe lifecycle and control music
    DisposableEffect(lifecycleOwner) {
        val observer = object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            fun onResume() {
                musicPlayer.play()
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            fun onPause() {
                musicPlayer.pause()
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            fun onDestroy() {
                musicPlayer.stop()
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        // Initial play
        musicPlayer.play()

        // Cleanup
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            musicPlayer.stop()
        }
    }

    // No UI component needed
    return
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val userRepository = UserRepository(this)

        // 🔥 Coba login
        userRepository.loginUser{ success, userId ->
            if (success) {
                Toast.makeText(this, "Login Berhasil! ID: $userId", Toast.LENGTH_SHORT).show()
                Log.d("MainActivity", "Login Berhasil! User ID: $userId")
            } else {
                Log.e("MainActivity", "User tidak ditemukan, membuat akun baru...")

                // 🔥 Jika tidak ditemukan, buat user baru
                val newUser = UserDataModel(
                    name = "User",
                    age = 6,
                    unlock_data = UserDataModel.UnlockData()
                )

                userRepository.createUser(newUser) { success, newUserId ->
                    if (success) {
                        Toast.makeText(
                            this,
                            "User Baru Dibuat! Login Sekarang...",
                            Toast.LENGTH_SHORT
                        ).show()
                        userRepository.loginUser { loginSuccess, loggedInUserId ->
                            if (loginSuccess) {
                                Log.d(
                                    "MainActivity",
                                    "Login Berhasil setelah buat akun! User ID: $loggedInUserId"
                                )
                            } else {
                                Log.e("MainActivity", "Login Gagal setelah membuat akun!")
                            }
                        }
                    } else {
                        Log.e("MainActivity", "Gagal membuat user baru!")
                    }
                }
            }
        }
        setContent {
            BackgroundMusicHandler()
            LexiLearnTheme {
                MyApp() // Menggunakan MyApp dengan tema LexiLearn
            }
        }
    }
}

@Composable
fun MyApp() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "home") {
        composable("splash") { SplashScreen(navController) }
        composable("login") { LoginScreen(navController) }
        composable("register") { RegisterScreen(navController) }
        composable("home") { HomeScreen(navController) }
        composable("read") { ReadScreen(navController) }
        composable("spell") { SpellScreen(navController) }
        composable("write") { WriteScreen(navController) }
        composable("screening") { ScreeningScreen(navController) }
//        composable("resultscreening") { ResultScreeningScreen(navController) }
        composable(
            route = "resultscreening/{totalScore}",
            arguments = listOf(navArgument("totalScore") { type = NavType.IntType })
        ) { backStackEntry ->
            val totalScore = backStackEntry.arguments?.getInt("totalScore") ?: 0
            ResultScreeningScreen(navController, totalScore)
        }
        composable("learnAlphabet") { LearnAlphabetScreen(navController) }
        composable("learnNumber") { LearnNumberScreen(navController) }
//        composable(
//            "navMaterial/{materialId}",
//            arguments = listOf(
//                navArgument("materialId") { type = NavType.StringType }
//            )
//        ) { backStackEntry ->
//            val materialId = backStackEntry.arguments?.getString("materialId") ?: ""
//            NavMaterialScreen(navController, materialId)
//        }
        composable("navMaterial/{materialId}") { backStackEntry ->
            val materialId = backStackEntry.arguments?.getString("materialId")
            NavMaterialScreen(navController, materialId ?: "")
        }
        composable("detailMaterial") { backStackEntry ->
            val materialList = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<List<MaterialDataModel>>("materialList")
            val indexValue = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<Int>("indexValue") ?: -1
            if (materialList != null) {
                DetailMaterialScreen(navController, materialList, indexValue)
            } else {
                println("masuk kondisi else")
            }
        }
        composable("quizScreen") { backStackEntry ->
            val selectedMaterialList = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<List<MaterialDataModel>>("selectedMaterialList")

            val typeQuiz = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<String>("typeQuiz") ?: "default"

            val indexValue = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<Int>("indexValue") ?: 0

            if (!selectedMaterialList.isNullOrEmpty()) {
                QuizScreen(navController, selectedMaterialList, typeQuiz, indexValue)
            } else {
                Text("Error: Data tidak tersedia")
            }
        }

//        composable("detailMaterial/{materialJson}") { backStackEntry ->
//            val jsonMaterial = backStackEntry.arguments?.getString("materialJson")
//
//            // 🔥 Konversi JSON String kembali ke List<MaterialDataModel>
//            val type = object : TypeToken<List<MaterialDataModel>>() {}.type
//            val materialList: List<MaterialDataModel> = Gson().fromJson(jsonMaterial, type)
//
//            DetailMaterialScreen(navController, materialList)
//        }
    }
}