package com.example.lexilearn

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.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 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 {
            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)
//        }
    }
}