package com.example.myapplication.components


import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.compose.itemKey
import com.example.myapplication.R
import com.example.myapplication.components.funs.createProductCard
import com.example.myapplication.database.entities.UserProductCart
import com.example.myapplication.viewModels.ProductViewModel

import com.example.myapplication.viewModels.UserViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import myColor3

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Main(
    navController: NavController,
    catalogId: Int,
    productViewModel: ProductViewModel = viewModel(factory = ProductViewModel.factory),
    userViewModel: UserViewModel = viewModel(factory = UserViewModel.factory)
) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    val products = when (catalogId) {
        0 -> productViewModel.getAll().collectAsLazyPagingItems()
        else -> productViewModel.getByCategory(catalogId).collectAsLazyPagingItems()
    }

    LaunchedEffect(Unit) {
        if (userViewModel.getUserId() == 0) {
            navController.navigate("authorization")
        }
    }
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(8.dp)
    ) {
        item{
            Button(
                onClick = {navController.navigate("addProduct")},
                colors = ButtonDefaults.buttonColors(
                    containerColor= Color.Transparent,
                    contentColor = myColor3
                ),
                contentPadding = PaddingValues(0.dp),
                modifier = Modifier.size(30.dp).padding(top = 10.dp)

            ) {
                Image(
                    painter = painterResource(id = R.drawable.add),
                    contentDescription = null,
                    modifier = Modifier.size(50.dp)
                )
            }
        }
        item {
            Text(
                text = "Товары:",
                fontSize = 28.sp,
                color = Color.Black,
                modifier = Modifier.padding(8.dp)
            )
        }
//        item {
//            products.forEach {
//                createProductCard(
//                    it.name,
//                    it.price,
//                    it.img,
//                    { navController.navigate("product/" + it.productId) })
//            }
//        }
        items (
            count = products.itemCount,
            key = products.itemKey { product -> product.productId!! }
        ) { index ->
            val it = products[index]!!
            createProductCard( it.name, it.price, it.img, { navController.navigate("product/" + it.productId)}){
                coroutineScope.launch {
                    kotlin.runCatching {
                        userViewModel.addProductCart(UserProductCart(userViewModel.getUserId(), it.productId!!))
                    }
                        .onSuccess {
                            val toast = Toast.makeText(context, "Добавлено", Toast.LENGTH_SHORT)
                            toast.show()
                            delay(500)
                            toast.cancel()
                        }
                        .onFailure {
                            val toast = Toast.makeText(context, "Уже есть в корзине", Toast.LENGTH_SHORT)
                            toast.show()
                            delay(500)
                            toast.cancel()
                        }
                }
            }
        }
    }

}
