package com.example.myapplication.components

import ButtonNice
import TextNice
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.R
import com.example.myapplication.components.common.myInput
import com.example.myapplication.components.templates.DropDown
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.ProductViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import myColor1
import myColor2

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddProduct(
    navController: NavController,
    id: Int = 0,
    itemViewModel: ProductViewModel = viewModel(factory = ProductViewModel.factory),
    categoryViewModel: CategoryViewModel = viewModel(factory = CategoryViewModel.factory)
)
{
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    val img = remember { mutableStateOf<Bitmap>(
        BitmapFactory.decodeResource(context.resources,
        R.drawable.product5
    )) }

    val imageData = remember { mutableStateOf<Uri?>(null) }
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
            imageData.value = uri
        }

    imageData.value?.let {
        if (Build.VERSION.SDK_INT < 28) {
            img.value = MediaStore.Images
                .Media.getBitmap(context.contentResolver, imageData.value)
        } else {
            val source = ImageDecoder
                .createSource(context.contentResolver, imageData.value!!)
            img.value = ImageDecoder.decodeBitmap(source)
        }
    }

    val categories = remember{ mutableListOf<Category>() }

    val nameState = remember { mutableStateOf("") }
    val infoState = remember { mutableStateOf("") }
    val priceState = remember { mutableStateOf("") }
    val categoryState = remember { mutableStateOf<Category?>(null) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            categories.addAll(categoryViewModel.getAll())
        }

        if(id != 0) {
            itemViewModel.getById(id).collect{
                nameState.value = it.name
            }
        }
    }
    Column(modifier = Modifier
        .fillMaxSize()
        .padding(start = 15.dp, end = 10.dp).verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally

    ) {
        TextNice("Добавление товара")
        myInput("Название", nameState)
        myInput("Описание", infoState)
        myInput("Цена", priceState)
        DropDown(categories, categoryState)

        Image(
            bitmap = img.value.asImageBitmap(),
            contentDescription = "editplaceholder",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(350.dp)
                .padding(8.dp)
                .align(Alignment.CenterHorizontally))
//        Button(
//            onClick = {
//                launcher.launch("image/*")
//            },
//            modifier = Modifier
//                .fillMaxWidth()
//                .padding(top = 10.dp)) {
//            Text("Выбрать картинку", fontSize = 20.sp)
//        }
        ButtonNice("Выбрать картинку", myColor1){
            launcher.launch("image/*")
        }
        ButtonNice("Сохранить", myColor2){
            coroutineScope.launch {
                itemViewModel.insert(Product(null, nameState.value,infoState.value, priceState.value.toDouble(), img.value, categoryState.value!!.id!!))
                navController.navigate("main/0")
            }
        }
//        Button(
//            onClick = {
//                coroutineScope.launch {
//                    itemViewModel.insert(Product(null, nameState.value,infoState.value, priceState.value.toDouble(), img.value, categoryState.value!!.id!!))
//                    navController.navigate("main/0")
//                }
//            },
//            modifier = Modifier
//                .fillMaxWidth()
//                .padding(top = 10.dp)) {
//            Text("Сохранить", fontSize = 20.sp)
//        }
    }
}


