package com.example.myapplication.ui.list

import android.graphics.BitmapFactory
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.R
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.entities.composeui.BikeViewModel
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.database.room.viewmodel.item.ItemListViewModel
import com.example.myapplication.ui.navigation.Screen
import kotlinx.coroutines.launch
import org.threeten.bp.format.DateTimeFormatter

@Composable
fun ItemList(
    bikeWithItemsViewModel: BikeViewModel,
    navController: NavController,
    viewModel: ItemListViewModel = viewModel(factory = AppViewModelProvider.Factory),
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val coroutineScope = rememberCoroutineScope()
    val bikeWithItems = bikeWithItemsViewModel.bikeUiState.bikeWithItems!!

    var getUser by remember { mutableStateOf(currentUserViewModel.user) }
    Log.d("Пожалуйста, работай", "${getUser?.uid}")

    LazyColumn {
        if (bikeWithItems.items.isEmpty()) {
            item {
                Text(
                    text = stringResource(R.string.Item_empty_description),
                    textAlign = TextAlign.Center,
                    style = MaterialTheme.typography.titleLarge
                )
            }
        } else {
            items(bikeWithItems.items, key = { it.uid }) { item ->
                val route = Screen.ItemEdit.route.replace(
                    "{id}", item.uid.toString()
                ).replace(
                    "{bikeId}", bikeWithItems.bike.uid.toString()
                )
                val dateFormatter = DateTimeFormatter.ofPattern("yyyy")
                val formattedDate = dateFormatter.format(item.dateTime)
                Column {
                    /*                Text(
                        text = formattedDate,
                        color = MaterialTheme.colorScheme.onBackground,
                    )*/
                    Box(modifier = Modifier
                        .padding(vertical = 7.dp)
                        .clickable {
                            navController.navigate(route)
                        }
                        .background(
                            color = MaterialTheme.colorScheme.primary,
                            shape = RoundedCornerShape(16.dp)
                        )) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            if (bikeWithItems.bike.image != null) Image(
                                bitmap = BitmapFactory.decodeByteArray(
                                    bikeWithItems.bike.image,
                                    0,
                                    bikeWithItems.bike.image.size
                                ).asImageBitmap(),
                                contentDescription = null,
                                modifier = Modifier
                                    .size(90.dp)
                                    .padding(4.dp)
                            )

                            Column(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(4.dp)
                            ) {
                                Text(
                                    text = "Вес: ${item.weight}\n" + "R: ${item.radius}\n" + "Цвет: ${item.colorbike}\n" + "Количество: ${item.availableCount}\n" + "Год: ${formattedDate}",
                                    color = MaterialTheme.colorScheme.onPrimary
                                )
                            }

                            IconButton(
                                onClick = {
                                    coroutineScope.launch {
                                        if (item.availableCount != 0) {
                                            getUser?.uid?.let {
                                                viewModel.addItemInCart(
                                                    userId = it,
                                                    itemId = item.uid
                                                )
                                            }
                                        }
                                    }
                                },
                            ) {
                                Icon(
                                    imageVector = Icons.Filled.Add,
                                    contentDescription = null,
                                    modifier = Modifier.size(24.dp),
                                    tint = MaterialTheme.colorScheme.onPrimary
                                )
                            }
                            if (getUser?.role == "admin") {
                                IconButton(
                                    onClick = {
                                        coroutineScope.launch {
                                            viewModel.deleteItem(item = item)
                                            bikeWithItemsViewModel.refreshState()
                                        }
                                    },
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Delete,
                                        contentDescription = null,
                                        modifier = Modifier.size(24.dp),
                                        tint = MaterialTheme.colorScheme.onPrimary
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

