package com.zyzf.coffeepreorder.ui.coffee

import android.content.Context
import android.content.res.Configuration
import android.net.Uri
import android.util.Log
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.border
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.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.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.outlined.Create
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedIconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SheetState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
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.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
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.paging.PagingData
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.CoffeeApplication
import com.zyzf.coffeepreorder.R
import com.zyzf.coffeepreorder.database.model.Coffee
import com.zyzf.coffeepreorder.ui.AppViewModelProvider
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.flow.MutableStateFlow
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CoffeeList(
    viewModel: CoffeeListViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val coroutineScope = rememberCoroutineScope()
    val coffeeListUiState = viewModel.coffeeListUiState.collectAsLazyPagingItems()
    val sheetState = rememberModalBottomSheetState()
    val openDialog = remember { mutableStateOf(false) }
    val coffee = remember { mutableStateOf(Coffee.getCoffee()) }
    val isImageChanged = remember { mutableStateOf(false) }
    var imageUri: Any? by remember { mutableStateOf(R.drawable.img) }
    var refreshing by remember { mutableStateOf(false) }
    fun refresh() = coroutineScope.launch {
        refreshing = true
        coffeeListUiState.refresh()
        refreshing = false
    }
    val state = rememberPullRefreshState(refreshing, ::refresh)
    val photoPicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()
    ) {
        if (it != null) {
            Log.d("PhotoPicker", "Selected URI: $it")
            imageUri = it
            isImageChanged.value = true
        } else {
            Log.d("PhotoPicker", "No media selected")
        }
    }
    Scaffold(
        topBar = {},
        floatingActionButton = {
            if (CoffeeApplication.currentUser?.role == "admin") {
                FloatingActionButton(
                    onClick = {
                        coroutineScope.launch {
                            coffee.value = Coffee.getCoffee()
                            openDialog.value = true
                        }
                    },
                    Modifier
                        .padding(all = 20.dp)
                ) {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = "Add",
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }
    ) { innerPadding ->
        Box (modifier = Modifier
            .padding(innerPadding)
            .pullRefresh(state)) {
            PullRefreshIndicator(refreshing = refreshing, state = state,
                modifier = Modifier
                    .zIndex(100f)
                    .align(Alignment.TopCenter)
            )
            CoffeeList(
                coffeeList = coffeeListUiState,
                onAddToCartClick = { coffeeUid: Int ->
                    coroutineScope.launch {
                        viewModel.addCoffeeToCart(coffeeUid = coffeeUid)
                    }
                }
            ) { currentCoffee: Coffee ->
                coroutineScope.launch {
                    coffee.value = currentCoffee
                    openDialog.value = true
                }
            }
        }
    }
    AddEditModalBottomSheet(
        coffee = coffee,
        sheetState = sheetState,
        openDialog = openDialog,
        onAddClick = { currentCoffee: Coffee, context: Context ->
            coroutineScope.launch {
                viewModel.createCoffee(currentCoffee, imageUri as Uri, context)
            }
        },
        onEditClick = { currentCoffee: Coffee, context: Context ->
            coroutineScope.launch {
                viewModel.editCoffee(currentCoffee, imageUri as Uri?, context)
            }
            isImageChanged.value = false
        },
        onDeleteClick = { currentCoffee: Coffee ->
            coroutineScope.launch {
                viewModel.deleteCoffee(currentCoffee)
            }
            isImageChanged.value = false
        },
        photoPicker = photoPicker,
        imageUri = imageUri,
        beforeOpen = {coffeeUid: Int ->
            if (coffeeUid != 0 && !isImageChanged.value) {
                imageUri = Uri.parse("https://zyzf.space/s/zXgFRTmbR4KMxMH/download?path=&files=coffee_image_" + coffee.value.uid +".png")
            }
        }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AddEditModalBottomSheet(
    coffee: MutableState<Coffee>,
    sheetState: SheetState,
    openDialog: MutableState<Boolean>,
    onAddClick: (coffee: Coffee, context: Context) -> Unit,
    onEditClick: (coffee: Coffee, context: Context) -> Unit,
    onDeleteClick: (coffee: Coffee) -> Unit,
    photoPicker: ManagedActivityResultLauncher<PickVisualMediaRequest, Uri?>,
    imageUri: Any?,
    beforeOpen: (coffeeUid: Int) -> Unit
) {
    beforeOpen(coffee.value.uid)
    var name: String by remember { mutableStateOf("")}
    var cost: Double by remember { mutableDoubleStateOf(0.0) }
    var ingredients: String by remember { mutableStateOf("")}
    name = coffee.value.name
    cost = coffee.value.cost
    ingredients = coffee.value.ingredients
    val context = LocalContext.current
    if (openDialog.value) {
        ModalBottomSheet(
            onDismissRequest = { openDialog.value = false },
            sheetState = sheetState
        ) {
            Column(modifier = Modifier
                .fillMaxWidth()
                .padding(all = 10.dp),
                horizontalAlignment = Alignment.CenterHorizontally) {
                OutlinedTextField(modifier = Modifier.fillMaxWidth(),
                    value = name, onValueChange = {name = it},
                    label = {
                        Text(stringResource(id = R.string.coffee_name))
                    },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
                )
                OutlinedTextField(modifier = Modifier.fillMaxWidth(),
                    value = cost.toString(), onValueChange = {cost = it.toDouble()},
                    label = {
                        Text(stringResource(id = R.string.coffee_cost))
                    },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
                )
                OutlinedTextField(modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 10.dp),
                    value = ingredients, onValueChange = {ingredients = it},
                    label = {
                        Text(stringResource(id = R.string.coffee_ingredients))
                    },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
                )
                AsyncImage(
                    modifier = Modifier
                        .size(100.dp)
                        .clip(RoundedCornerShape(50.dp))
                        .border(
                            2.dp,
                            MaterialTheme.colorScheme.outline,
                            shape = RoundedCornerShape(50.dp)
                        )
                        .clickable {
                            photoPicker.launch(
                                PickVisualMediaRequest(
                                    ActivityResultContracts.PickVisualMedia.ImageOnly
                                )
                            )
                        }
                        .border(
                            2.dp,
                            MaterialTheme.colorScheme.outlineVariant,
                            shape = RoundedCornerShape(50.dp)
                        ),
                    contentDescription = "Кофе",
                    error = painterResource(R.drawable.ic_broken_image),
                    placeholder = painterResource(R.drawable.loading_img),
                    contentScale = ContentScale.Crop,
                    model = ImageRequest
                        .Builder(context = LocalContext.current)
                        .data(imageUri)
                        .crossfade(true)
                        .build(),
                )
                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
                    if (coffee.value.uid == 0) {
                        Button(onClick = {
                            onAddClick(Coffee(coffee.value.uid, name, cost, ingredients), context)
                            openDialog.value = false
                        }, modifier = Modifier.padding(0.dp, 10.dp, 0.dp, 30.dp)) {
                            Text("Добавить")
                        }
                    } else {
                        Button(onClick = {
                            onEditClick(Coffee(coffee.value.uid, name, cost, ingredients), context)
                            openDialog.value = false
                        }, modifier = Modifier.padding(0.dp, 10.dp, 0.dp, 30.dp)) {
                            Text("Изменить")
                        }
                        Spacer(modifier = Modifier.padding(all = 20.dp))
                        Button(onClick = {
                            onDeleteClick(coffee.value)
                            openDialog.value = false
                        }, modifier = Modifier.padding(0.dp, 10.dp, 0.dp, 30.dp)) {
                            Text("Удалить")
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun CoffeeList(
    coffeeList: LazyPagingItems<Coffee>,
    onAddToCartClick: (coffeeUid: Int) -> Unit,
    onEditClick: (coffee: Coffee) -> Unit
) {
    LazyColumn(
        horizontalAlignment = Alignment.CenterHorizontally) {
        items(
            count = coffeeList.itemCount,
            key = coffeeList.itemKey(),
            contentType = coffeeList.itemContentType()
        ) {index ->
            val coffee = coffeeList[index]
            coffee?.let {
                CoffeeListItem(
                    coffee = coffee,
                    onAddToCartClick = onAddToCartClick,
                    onEditClick = onEditClick
                )
            }
        }
    }
}

@Composable
private fun CoffeeListItem(
    coffee: Coffee,
    onAddToCartClick: (coffeeUid: Int) -> Unit,
    onEditClick: (coffee: Coffee) -> Unit
) {
    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)) {
            Text(text = coffee.name, 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 = {
                        onAddToCartClick(coffee.uid)
                    },
                    shape = CircleShape,
                    modifier = Modifier.fillMaxWidth(fraction = 0.75f)
                ) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "Favorite",
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(Modifier.size(ButtonDefaults.IconSpacing))
                    Text(text = "В корзину")
                }
                if (CoffeeApplication.currentUser?.role == "admin") {
                    OutlinedIconButton(
                        onClick = {
                            onEditClick(coffee)
                        },
                        Modifier
                            .padding(start = 10.dp)
                            .clip(CircleShape)
                    ) {
                        Icon(
                            imageVector = Icons.Outlined.Create,
                            contentDescription = "Favorite",
                            modifier = Modifier.size(20.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 CoffeeListPreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            CoffeeList(
                coffeeList = MutableStateFlow(
                    PagingData.from((1..20).map { i -> Coffee.getCoffee(i) })
                ).collectAsLazyPagingItems(),
                onAddToCartClick = {}
            ) {}
        }
    }
}


@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 CoffeeEmptyListPreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            CoffeeList(
                coffeeList = MutableStateFlow(
                    PagingData.empty<Coffee>()
                ).collectAsLazyPagingItems(),
                onAddToCartClick = {}
            ) {}
        }
    }
}