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.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.UserModel
import com.example.lexilearn.data.repository.MaterialRepository
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 repository = MaterialRepository(this)

        // 🔥 Default email & password
        val email = "example@gmail.com"
        val password = "example123"

        // 🔥 Coba login
        repository.loginUser(email, password) { 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 = UserModel(
                    email = email,
                    name = "Example User",
                    password = password,
                    unlock_data = UserModel.UnlockData()
                )

                repository.createUser(newUser) { success, newUserId ->
                    if (success) {
                        Toast.makeText(this, "User Baru Dibuat! Login Sekarang...", Toast.LENGTH_SHORT).show()
                        repository.loginUser(email, password) { 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 {
            MyApp()
        }
    }
}

@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("learnAlphabet") { LearnAlphabetScreen(navController) }
        composable("learnNumber") { LearnNumberScreen(navController) }
        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")

            if (materialList != null) {
                DetailMaterialScreen(navController, materialList)
            }else{
                println("masuk kondisi else")
            }
        }
        composable("quizScreen") { backStackEntry ->
            val selectedMaterialList = navController.previousBackStackEntry
                ?.savedStateHandle
                ?.get<List<MaterialDataModel>>("selectedMaterialList")

            val selectedMaterial = selectedMaterialList?.firstOrNull()

            if (selectedMaterial != null) {
                QuizScreen(navController, selectedMaterial)
            } 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)
//        }
    }
}