package com.example.myapplication.components


import ButtonNice
import TextNice
import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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 com.example.myapplication.components.funs.ProductCardInCart
import com.example.myapplication.components.funs.createProductCard
import com.example.myapplication.database.AppDb
import com.example.myapplication.database.entities.Product
import com.example.myapplication.viewModels.UserViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import myColor4

@Composable
fun Cart(navController: NavController, userViewModel: UserViewModel = viewModel(factory = UserViewModel.factory)){

    val coroutineScope = rememberCoroutineScope()
    val products = remember { mutableStateListOf<Product>() }
    val sumPrice = remember { mutableStateOf(0.0) }

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

        withContext(Dispatchers.IO) {
            val data = userViewModel.getUserProductsCartById(userViewModel.getUserId())
            products.clear()
            sumPrice.value = 0.0;
            data.products.forEach {
                sumPrice.value += it.price
                products.add(it)
            }
        }
    }

    LazyColumn (contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)){
        item {
            TextNice("Корзина")
        }

        item{
            products.forEach{
                ProductCardInCart(it.name, it.price, it.img){
                        coroutineScope.launch {
                            userViewModel.deleteCartProduct(userViewModel.getUserId(), it.productId!!)
                            sumPrice.value -= it.price
                            products.remove(it)
                    }
                }
            }
        }

        item {
                ButtonNice(text = "Оплатить: " + sumPrice.value.toString() + "Р", color = myColor4)
        }
    }

}
