package com.example.myapplication.ui.list

import android.content.res.Configuration
import android.graphics.BitmapFactory
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.Spacer
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.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.outlined.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.DismissDirection
import androidx.compose.material3.DismissState
import androidx.compose.material3.DismissValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.SwipeToDismiss
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDismissState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapplication.R
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.model.item.Item
import com.example.myapplication.database.room.model.item.ItemFromCart
import com.example.myapplication.database.room.viewmodel.cart.CartUiState
import com.example.myapplication.database.room.viewmodel.cart.CartViewModel
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.ui.theme.PmudemoTheme
import com.example.myapplication.ui.view.ErroreView
import kotlinx.coroutines.launch
import org.threeten.bp.format.DateTimeFormatter

@Composable
fun CartList(
    viewModel: CartViewModel = viewModel(factory = AppViewModelProvider.Factory),
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val coroutineScope = rememberCoroutineScope()
    val cartUiState = viewModel.cartUiState
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    // Проверяем, есть ли у пользователя uid
    if (getUser?.uid != null) {
        LaunchedEffect(Unit) {
            getUser?.uid?.let { viewModel.refreshState(it) }
        }

        CartList(
            cartUiState = cartUiState,
            modifier = Modifier
                .padding(all = 10.dp),
            onSwipe = { item: ItemFromCart ->
                coroutineScope.launch {
                    getUser?.uid?.let {
                        viewModel.removeFromCart(
                            item = Item(
                                uid = item.uid,
                                dateTime = item.dateTime,
                                weight = item.weight,
                                radius = item.radius,
                                colorbike = item.colorbike,
                                maxCount = 0,
                                bikeId = item.bikeId
                            ), user = it
                        )
                    }
                }
            },
            onChangeCount = { item: ItemFromCart, count: Int ->
                coroutineScope.launch {
                    getUser?.uid?.let {
                        viewModel.updateFromCart(
                            item = Item(
                                uid = item.uid,
                                dateTime = item.dateTime,
                                weight = item.weight,
                                radius = item.radius,
                                colorbike = item.colorbike,
                                maxCount = 0,
                                bikeId = item.bikeId
                            ), userId = it, count = count, availableCount = item.availableCount
                        )
                    }
                }
            },
            onAddToRent = { items: List<ItemFromCart> ->
                coroutineScope.launch {
                    getUser?.uid?.let { viewModel.addToRent(items = items, userId = it) }
                }
            }
        )
    } else {
        ErroreView()
    }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CartList(
    cartUiState: CartUiState,
    modifier: Modifier,
    onSwipe: (ItemFromCart) -> Unit,
    onChangeCount: (ItemFromCart, Int) -> Unit,
    onAddToRent: (List<ItemFromCart>) -> Unit
) {
    LazyColumn(
        modifier = modifier
    ) {
        items(cartUiState.itemList, key = { it.uid.toString() }) { item ->
            val dismissState: DismissState = rememberDismissState(
                positionalThreshold = { 200.dp.toPx() }
            )

            if (dismissState.isDismissed(direction = DismissDirection.EndToStart)) {
                onSwipe(item)
            }

            SwipeToDelete(
                dismissState = dismissState,
                item = item,
                onChangeCount = onChangeCount
            )
        }
    }
    Column {
        Spacer(modifier = Modifier.weight(1f))

        Button(
            onClick = { onAddToRent(cartUiState.itemList) },
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) { Text("Арендовать") }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SwipeToDelete(
    dismissState: DismissState,
    item: ItemFromCart,
    onChangeCount: (ItemFromCart, Int) -> Unit,
) {
    SwipeToDismiss(
        state = dismissState,
        directions = setOf(
            DismissDirection.EndToStart
        ),
        background = {
            val backgroundColor by animateColorAsState(
                when (dismissState.targetValue) {
                    DismissValue.DismissedToStart -> Color.Red.copy(alpha = 0.8f)
                    else -> MaterialTheme.colorScheme.background
                },
                label = ""
            )
            val iconScale by animateFloatAsState(
                targetValue = if (dismissState.targetValue == DismissValue.DismissedToStart) 1.3f else 0.5f,
                label = ""
            )
            Box(
                Modifier
                    .fillMaxSize()
                    .background(color = backgroundColor)
                    .padding(end = 16.dp),
                contentAlignment = Alignment.CenterEnd
            ) {
                Icon(
                    modifier = Modifier.scale(iconScale),
                    imageVector = Icons.Outlined.Delete,
                    contentDescription = "Delete",
                    tint = Color.White
                )
            }
        },
        dismissContent = {
            ItemListItem(
                item = item,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(MaterialTheme.colorScheme.secondary),
                onChangeCount = onChangeCount
            )
        }
    )
}

@Composable
private fun ItemListItem(
    item: ItemFromCart,
    modifier: Modifier = Modifier,
    onChangeCount: (ItemFromCart, Int) -> Unit,
) {
    var currentCount by remember { mutableStateOf(item.count) }

    val dateFormatter = DateTimeFormatter.ofPattern("yyyy")
    val formattedDate = dateFormatter.format(item.dateTime)
    Column {
/*        Text(
            text = formattedDate,
            color = MaterialTheme.colorScheme.onBackground,
        )*/
        Box(
            modifier = modifier
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                if (item.bike.image != null)
                    Image(
                        bitmap = BitmapFactory.decodeByteArray(
                            item.bike.image,
                            0,
                            item.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.bike.name}\n" +
                                "Вес: ${item.weight}\n" +
                                "R: ${item.radius}\n" +
                                "Цвет: ${item.colorbike}\n" +
                                "${currentCount}/${item.availableCount}\n" +
                                "Год: ${formattedDate}",
                        color = MaterialTheme.colorScheme.onSecondary
                    )
                }

                Box(
                    modifier = Modifier
                        .background(
                            color = MaterialTheme.colorScheme.onBackground,
                            shape = RoundedCornerShape(10.dp)
                        ) // Задаем фон для кнопок
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        IconButton(
                            onClick = { onChangeCount(item, --currentCount) }
                        ) {
                            Icon(
                                imageVector = ImageVector.vectorResource(id = R.drawable.minus),
                                contentDescription = "Уменьшить",
                                tint = MaterialTheme.colorScheme.background,
                                modifier = Modifier.size(10.dp)
                            )
                        }

                        Text(
                            text = "$currentCount",
                            color = MaterialTheme.colorScheme.background
                        )

                        IconButton(
                            onClick = {
                                onChangeCount(
                                    item,
                                    if (currentCount != item.availableCount) ++currentCount else currentCount
                                )
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.Add,
                                contentDescription = "Увеличить",
                                tint = MaterialTheme.colorScheme.background,
                                modifier = Modifier.size(10.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun CartPreview() {
    PmudemoTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            CartList()
        }
    }
}
