package com.zyzf.coffeepreorder.ui.cart

import android.content.res.Configuration
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
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.Clear
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemContentType
import androidx.paging.compose.itemKey
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.zyzf.coffeepreorder.R
import com.zyzf.coffeepreorder.database.model.Coffee
import com.zyzf.coffeepreorder.ui.AppViewModelProvider
import com.zyzf.coffeepreorder.ui.navigation.Screen
import com.zyzf.coffeepreorder.ui.theme.CoffeePreorderTheme
import eu.bambooapps.material3.pullrefresh.PullRefreshIndicator
import eu.bambooapps.material3.pullrefresh.pullRefresh
import eu.bambooapps.material3.pullrefresh.rememberPullRefreshState
import kotlinx.coroutines.launch


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Cart(
    navController: NavController?,
    viewModel: CartViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val coroutineScope = rememberCoroutineScope()
    val coffeeListUiState = viewModel.coffeeListUiState.collectAsLazyPagingItems()
    val openDialog = remember { mutableStateOf(false) }
    val coffee = remember { mutableStateOf(Coffee.getCoffee()) }
    var refreshing by remember { mutableStateOf(false) }
    fun refresh() = coroutineScope.launch {
        refreshing = true
        coffeeListUiState.refresh()
        refreshing = false
    }
    val state = rememberPullRefreshState(refreshing, ::refresh)
    Scaffold(
        topBar = {},
        floatingActionButton = {
            ExtendedFloatingActionButton(
                onClick = { navController?.navigate(Screen.Order.route) },
                icon = { Icon(Icons.Filled.Add, "Сделать заказ") },
                text = { Text(text = "Сделать заказ") },
                modifier = Modifier
                    .padding(all = 20.dp),
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                contentColor = MaterialTheme.colorScheme.primary
            )
        }
    ) { innerPadding ->
        Box (modifier = Modifier
            .padding(innerPadding)
            .pullRefresh(state)) {
            PullRefreshIndicator(refreshing = refreshing, state = state,
                modifier = Modifier
                    .zIndex(100f)
                    .align(Alignment.TopCenter)
            )
            CartList(
                coffeeList = coffeeListUiState,
                onDeleteFromCartClick = {currentCoffee: Coffee ->
                    coffee.value = currentCoffee
                    openDialog.value = true
                }
            ) { coffeeId: Int ->
                viewModel.getCountForCoffee(coffeeId)
            }
        }
    }
    DeleteFromCartAlertDialog(
        openDialog = openDialog
    ) {
        coroutineScope.launch {
            viewModel.deleteCoffeeFromCart(coffee.value)
        }
    }
}

@Composable
private fun CartList(
    coffeeList: LazyPagingItems<Coffee>,
    onDeleteFromCartClick: (coffee: Coffee) -> Unit,
    getCoffeeCount: (coffeeId: Int) -> Double
) {
    LazyColumn(
        horizontalAlignment = Alignment.CenterHorizontally) {
        items(
            count = coffeeList.itemCount,
            key = coffeeList.itemKey(),
            contentType = coffeeList.itemContentType()
        ) {index ->
            val coffee = coffeeList[index]
            coffee?.let {
                CartListItem(
                    coffee = coffee,
                    onDeleteFromCartClick = onDeleteFromCartClick,
                    getCoffeeCount = getCoffeeCount
                )
            }
        }
    }
}

@Composable
private fun CartListItem (
    coffee: Coffee,
    onDeleteFromCartClick: (coffee: Coffee) -> Unit,
    getCoffeeCount: (coffeeId: Int) -> Double
) {
    Row(modifier = Modifier
        .fillMaxWidth()
        .heightIn(max = 140.dp)
        .padding(bottom = 10.dp, top = 10.dp),
        horizontalArrangement = Arrangement.SpaceAround) {
        AsyncImage(
            model = ImageRequest.Builder(context = LocalContext.current).data("https://zyzf.space/s/zXgFRTmbR4KMxMH/download?path=&files=coffee_image_" + coffee.uid +".png")
                .crossfade(true).build(),
            error = painterResource(R.drawable.ic_broken_image),
            placeholder = painterResource(R.drawable.loading_img),
            contentDescription = "Кофе",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(100.dp)
                .clip(RoundedCornerShape(50.dp))
        )
        Column(
            Modifier
                .weight(2f)
                .padding(start = 20.dp)) {
            val coffeeCount: Double = getCoffeeCount(coffee.uid)
            val currentCoffeeName: String = if (coffeeCount > 1) {
                coffee.name + " x" + coffeeCount.toString()
            } else {
                coffee.name
            }
            Text(text = currentCoffeeName, fontSize = 25.sp)
            Text(text = String.format("%.2f", coffee.cost), fontSize = 20.sp)
            Text(text = coffee.ingredients, fontSize = 15.sp)
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(top = 5.dp)) {
                Button(
                    onClick = { onDeleteFromCartClick(coffee) },
                    shape = CircleShape,
                    modifier = Modifier.padding(start = 10.dp, end = 10.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer,
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "Favorite",
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(Modifier.size(ButtonDefaults.IconSpacing))
                    Text(text = "Удалить из корзины")
                }
            }
        }
    }
}

@Composable
private fun DeleteFromCartAlertDialog(
    openDialog: MutableState<Boolean>,
    onConfirmClick: () -> Unit
) {
    if (openDialog.value) {
        AlertDialog(
            icon = {
                Icon(Icons.Default.Clear, contentDescription = "Example Icon")
            },
            title = {
                Text(text = "Подтверждение")
            },
            text = {
                Text(text = "Вы хотите удалить элемент из корзины?")
            },
            onDismissRequest = {
                openDialog.value = false
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        onConfirmClick()
                        openDialog.value = false
                    }
                ) {
                    Text("Да")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                    }
                ) {
                    Text("Нет")
                }
            }
        )
    }
}

@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 CoffeeListPreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            Cart(navController = null)
        }
    }
}