package com.pixelized.desktop.lwa.ui.composable.character.item

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.pixelized.desktop.lwa.ui.composable.character.LwaDialog
import com.pixelized.desktop.lwa.ui.composable.image.DesaturatedAsyncImage
import com.pixelized.desktop.lwa.ui.composable.textfield.LwaTextField
import com.pixelized.desktop.lwa.ui.composable.textfield.LwaTextFieldUio
import com.pixelized.desktop.lwa.ui.theme.color.component.LwaTextFieldColors
import com.pixelized.desktop.lwa.ui.theme.lwa
import com.pixelized.desktop.lwa.utils.extention.calculatePaddings
import com.pixelized.desktop.lwa.utils.rememberSaturationFilter
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character__inventory__equip__action
import lwacharactersheet.composeapp.generated.resources.character__inventory__inventory__dialog__action
import lwacharactersheet.composeapp.generated.resources.character__inventory__inventory__dialog__consume_action
import lwacharactersheet.composeapp.generated.resources.character__inventory__inventory__dialog__count_action
import lwacharactersheet.composeapp.generated.resources.character__inventory__inventory__dialog__throw_action
import lwacharactersheet.composeapp.generated.resources.character__inventory__unequip__action
import lwacharactersheet.composeapp.generated.resources.ic_close_24dp
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource

@Stable
data class ItemDetailDialogUio(
    val characterSheetId: String,
    val inventoryId: String?,
    val itemId: String,
    // meta
    val label: String,
    val description: String,
    val image: String?,
    val count: Float,
    // options
    val countable: LwaTextFieldUio?,
    val consumable: Boolean,
    val equipped: Boolean,
    val equipable: Boolean,
)

@Stable
object ItemDetailDialogDefault {
    @Stable
    val paddings = PaddingValues(top = 16.dp, start = 16.dp, end = 16.dp, bottom = 8.dp)

    @Stable
    val spacings = 8.dp
}

@Composable
fun ItemDetailDialog(
    dialog: State<ItemDetailDialogUio?>,
    paddings: PaddingValues = ItemDetailDialogDefault.paddings,
    spacings: Dp = ItemDetailDialogDefault.spacings,
    onDismissRequest: () -> Unit,
    onConfirm: (ItemDetailDialogUio) -> Unit,
    onAddItem: (ItemDetailDialogUio) -> Unit,
    onEquip: (ItemDetailDialogUio) -> Unit,
    onConsume: (ItemDetailDialogUio) -> Unit,
    onThrow: (ItemDetailDialogUio) -> Unit,
) {
    LwaDialog(
        state = dialog,
        onDismissRequest = onDismissRequest,
        onConfirm = { dialog.value?.let(onConfirm) ?: onDismissRequest },
    ) { state ->
        val (_, top, end, _) = paddings.calculatePaddings()

        takeIf { state.image?.isNotEmpty() == true }?.let {
            DesaturatedAsyncImage(
                modifier = Modifier
                    .size(64.dp * 2)
                    .align(alignment = Alignment.TopEnd),
                colorFilter = rememberSaturationFilter(),
                model = state.image,
                contentScale = ContentScale.Crop,
                alignment = Alignment.TopCenter,
                filterQuality = FilterQuality.High,
                contentDescription = null,
            )
        }

        Column(
            modifier = Modifier.padding(paddingValues = paddings),
            verticalArrangement = Arrangement.spacedBy(space = spacings)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
            ) {
                Text(
                    modifier = Modifier.weight(weight = 1f),
                    style = MaterialTheme.typography.h5,
                    fontWeight = FontWeight.Bold,
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1,
                    text = state.label,
                )
                IconButton(
                    modifier = Modifier.offset(x = end, y = -top),
                    onClick = onDismissRequest,
                ) {
                    Icon(
                        painter = painterResource(Res.drawable.ic_close_24dp),
                        tint = MaterialTheme.lwa.colorScheme.base.primary,
                        contentDescription = null,
                    )
                }
            }

            Text(
                style = MaterialTheme.typography.body1,
                text = state.description,
            )

            Spacer(modifier = Modifier)

            AnimatedContent(
                targetState = state.inventoryId,
                transitionSpec = { fadeIn() togetherWith fadeOut() },
            ) {
                when (it) {
                    null -> Row(
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        if (state.countable != null) {
                            LwaTextField(
                                modifier = Modifier.width(width = 128.dp).height(32.dp),
                                colors = LwaTextFieldColors(
                                    backgroundColor = MaterialTheme.lwa.colorScheme.elevated.base2dp,
                                ),
                                field = state.countable,
                            )
                        }
                        Spacer(
                            modifier = Modifier.weight(1f),
                        )
                        TextButton(
                            onClick = { onAddItem(state) },
                        ) {
                            Text(
                                text = stringResource(Res.string.character__inventory__inventory__dialog__action)
                            )
                        }
                    }

                    else -> Column(
                        verticalArrangement = Arrangement.spacedBy(space = spacings)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(space = spacings),
                            verticalAlignment = Alignment.Bottom,
                        ) {
                            if (state.countable != null) {
                                LwaTextField(
                                    modifier = Modifier.width(width = 128.dp),
                                    colors = LwaTextFieldColors(
                                        backgroundColor = MaterialTheme.lwa.colorScheme.elevated.base2dp,
                                    ),
                                    field = state.countable,
                                )
                                TextButton(
                                    modifier = Modifier
                                        .height(height = 56.dp)
                                        .background(
                                            color = MaterialTheme.lwa.colorScheme.elevated.base2dp,
                                            shape = MaterialTheme.shapes.small,
                                        ),
                                    enabled = state.countable.errorFlow.collectAsState().value.not(),
                                    onClick = { onConfirm(state) }
                                ) {
                                    Text(
                                        text = stringResource(Res.string.character__inventory__inventory__dialog__count_action),
                                    )
                                }
                            }
                            Spacer(
                                modifier = Modifier.weight(weight = 1f),
                            )
                            TextButton(
                                onClick = { onThrow(state) },
                            ) {
                                Text(
                                    text = stringResource(Res.string.character__inventory__inventory__dialog__throw_action),
                                )
                            }
                            if (state.equipable) {
                                TextButton(
                                    onClick = { onEquip(state) },
                                ) {
                                    AnimatedContent(
                                        targetState = state.equipped,
                                    ) {
                                        Text(
                                            text = stringResource(
                                                when (it) {
                                                    true -> Res.string.character__inventory__unequip__action
                                                    else -> Res.string.character__inventory__equip__action
                                                }
                                            )
                                        )
                                    }
                                }
                            }
                            if (state.consumable) {
                                TextButton(
                                    onClick = { onConsume(state) },
                                ) {
                                    Text(
                                        text = stringResource(Res.string.character__inventory__inventory__dialog__consume_action),
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}