package com.example.myapplication.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.myapplication.components.templates.CatalogItems
import com.example.myapplication.components.templates.CategoryItem
import com.example.myapplication.database.AppDb
import com.example.myapplication.database.entities.Category
import com.example.myapplication.database.entities.Product
import com.example.myapplication.viewModels.CategoryViewModel
import com.example.myapplication.viewModels.UserViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


@Composable
fun Сategory(navController: NavController,
             userViewModel: UserViewModel = viewModel(factory = UserViewModel.factory),
             categoryViewModel: CategoryViewModel = viewModel(factory = CategoryViewModel.factory)
) {
    Column(
        modifier = Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 20.dp,),
        horizontalAlignment = Alignment.End
    ) {

        val context = LocalContext.current
        val categories = remember { mutableStateListOf<Category>() }

        LaunchedEffect(Unit) {
            if(userViewModel.getUserId() == 0) {
                navController.navigate("authorization")
            }

            withContext(Dispatchers.IO) {
                categories.addAll(categoryViewModel.getAll())
            }
        }
        categories.forEach{
            CategoryItem(it.name, { navController.navigate("main/" + it.id)})
        }
    }
}

