package com.pixelized.desktop.lwa.ui.screen.campaign.player.detail.inventory.item

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.ExperimentalFoundationApi
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
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.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
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.DpSize
import androidx.compose.ui.unit.dp
import coil3.PlatformContext
import coil3.request.ImageRequest
import com.pixelized.desktop.lwa.ui.composable.decoratedBox.DecoratedBox
import com.pixelized.desktop.lwa.ui.composable.image.DesaturatedAsyncImage
import com.pixelized.desktop.lwa.ui.composable.image.LwaAsyncImage
import com.pixelized.desktop.lwa.ui.composable.tooltip.TooltipLayout
import com.pixelized.desktop.lwa.ui.theme.lwa
import com.pixelized.desktop.lwa.utils.extention.calculatePaddings
import com.pixelized.desktop.lwa.utils.extention.ribbon
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__unequip__action
import lwacharactersheet.composeapp.generated.resources.character__inventory__use__action
import org.jetbrains.compose.resources.stringResource

@Stable
data class InventoryItemUio(
    val characterSheetId: String,
    val inventoryId: String,
    val itemId: String,
    val icon: String?,
    val label: String,
    val count: String,
    val equipped: Boolean,
    val stackable: Boolean,
    val consumable: Boolean,
    val equipable: Boolean,
    val tooltips: Tooltips?,
) {
    @Stable
    data class Tooltips(
        val label: String,
        val description: String,
        val image: String?,
    )
}

@Stable
object GMCharacterPreviewDefault {
    @Stable
    val paddings = PaddingValues(horizontal = 8.dp)

    @Stable
    val toolTipPaddings = PaddingValues(all = 16.dp)

    val icon: DpSize = DpSize(width = 32.dp, height = 32.dp)

    @Stable
    val spacing: Dp = 8.dp
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun InventoryItem(
    modifier: Modifier = Modifier,
    padding: PaddingValues = GMCharacterPreviewDefault.paddings,
    toolTipPaddings: PaddingValues = GMCharacterPreviewDefault.toolTipPaddings,
    spacing: Dp = GMCharacterPreviewDefault.spacing,
    icon: DpSize = GMCharacterPreviewDefault.icon,
    item: InventoryItemUio,
    onClick: () -> Unit,
    onConsume: () -> Unit,
    onEquip: () -> Unit,
) {
    val (start, top, end, bottom) = padding.calculatePaddings()
    val (_, toolTop, toolEnd, _) = toolTipPaddings.calculatePaddings()

    TooltipLayout(
        modifier = modifier,
        tips = item.tooltips,
        tooltip = { tooltips ->
            DecoratedBox(
                modifier = Modifier.width(width = 448.dp),
            ) {
                Surface {
                    Box(
                        modifier = Modifier.padding(paddingValues = toolTipPaddings)
                    ) {
                        takeIf { tooltips.image?.isNotEmpty() == true }?.let {
                            DesaturatedAsyncImage(
                                modifier = Modifier
                                    .size(size = 96.dp)
                                    .align(alignment = Alignment.TopEnd)
                                    .offset(x = toolEnd, y = -toolTop),
                                colorFilter = rememberSaturationFilter(),
                                model = tooltips.image,
                                contentScale = ContentScale.Crop,
                                alignment = Alignment.TopCenter,
                                filterQuality = FilterQuality.High,
                                contentDescription = null,
                            )
                        }
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(space = spacing)
                        ) {
                            Text(
                                style = MaterialTheme.typography.body2,
                                fontWeight = FontWeight.Bold,
                                text = tooltips.label,
                            )
                            Text(
                                style = MaterialTheme.typography.caption,
                                fontWeight = FontWeight.Light,
                                text = tooltips.description,
                            )
                        }
                    }
                }
            }
        },
        content = {
            Row(
                modifier = Modifier
                    .clip(shape = MaterialTheme.lwa.shapes.item)
                    .clickable(onClick = onClick)
                    .background(color = MaterialTheme.lwa.colorScheme.elevated.base2dp)
                    .ribbon(
                        color = when (item.equipped) {
                            true -> MaterialTheme.lwa.colorScheme.base.primary
                            else -> Color.Transparent
                        }
                    )
                    .minimumInteractiveComponentSize()
                    .fillMaxWidth()
                    .padding(start = start, end = end)
                    .then(other = modifier),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Row(
                    modifier = Modifier.weight(weight = 1f),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(space = spacing),
                ) {
                    Box(
                        modifier = Modifier
                            .height(height = icon.height)
                            .widthIn(min = icon.width, max = icon.width * 3)
                            .graphicsLayer { clip = false },
                        contentAlignment = Alignment.CenterStart,
                    ) {
                        Box(
                            modifier = Modifier
                                .size(size = icon)
                                .background(
                                    color = MaterialTheme.lwa.colorScheme.elevated.base4dp,
                                    shape = CircleShape,
                                )
                        )

                        LwaAsyncImage(
                            modifier = Modifier
                                .size(size = icon)
                                .aspectRatio(ratio = 1f, matchHeightConstraintsFirst = true),
                            model = ImageRequest.Builder(context = PlatformContext.INSTANCE)
                                .data(data = item.icon)
                                .size(size = 64)
                                .build(),
                            contentScale = ContentScale.Crop,
                            filterQuality = FilterQuality.Medium,
                            contentDescription = null,
                        )
                        if (item.stackable) {
                            AnimatedContent(
                                modifier = Modifier
                                    .align(alignment = Alignment.BottomEnd)
                                    .offset(y = 4.dp),
                                targetState = item.count,
                                transitionSpec = {
                                    val enter = fadeIn() + slideInVertically { -8 }
                                    val exit = fadeOut() + slideOutVertically { 8 }
                                    enter togetherWith exit using SizeTransform(clip = false)
                                },
                            ) {
                                Box(
                                    contentAlignment = Alignment.Center,
                                ) {
                                    Text(
                                        style = MaterialTheme.lwa.typography.inventory.countOutline,
                                        overflow = TextOverflow.Ellipsis,
                                        maxLines = 1,
                                        text = it,
                                    )
                                    Text(
                                        style = MaterialTheme.lwa.typography.inventory.count,
                                        overflow = TextOverflow.Ellipsis,
                                        maxLines = 1,
                                        text = it,
                                    )
                                }
                            }
                        }
                    }
                    Text(
                        modifier = Modifier
                            .padding(top = top, bottom = bottom)
                            .weight(weight = 1f, fill = false),
                        style = MaterialTheme.lwa.typography.inventory.label,
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 1,
                        text = item.label,
                    )
                }
                Row(
                    modifier = Modifier
                        .padding(top = top, bottom = bottom)
                        .offset(x = end - spacing),
                    horizontalArrangement = Arrangement.spacedBy(space = spacing),
                ) {
                    if (item.consumable) {
                        TextButton(
                            onClick = onConsume,
                        ) {
                            Text(text = stringResource(Res.string.character__inventory__use__action))
                        }
                    }
                    if (item.equipable) {
                        TextButton(
                            onClick = onEquip,
                        ) {
                            AnimatedContent(
                                targetState = item.equipped,
                            ) {
                                Text(
                                    text = stringResource(
                                        when (it) {
                                            true -> Res.string.character__inventory__unequip__action
                                            else -> Res.string.character__inventory__equip__action
                                        }
                                    )
                                )
                            }
                        }
                    }
                }
            }
        },
    )
}