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

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
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.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
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.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
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.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.decoratedBox.DecoratedBox
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.composable.tooltip.TooltipLayout
import com.pixelized.desktop.lwa.ui.theme.color.component.LwaTextFieldColors
import com.pixelized.desktop.lwa.ui.theme.lwa
import com.pixelized.desktop.lwa.utils.rememberSaturationFilter
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character__inventory__inventory__dialog__title
import lwacharactersheet.composeapp.generated.resources.ic_cancel_24dp
import lwacharactersheet.composeapp.generated.resources.ic_close_24dp
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource

@Stable
data class InventoryDialogUio(
    val characterSheetId: String,
    val filter: LwaTextFieldUio,
    val items: List<Item>,
) {
    @Stable
    data class Item(
        val itemId: String,
        val label: String,
        val tooltips: ToolTip?,
    ) {
        @Stable
        data class ToolTip(
            val label: String,
            val description: String,
            val image: String?,
        )
    }
}

@Stable
object InventoryDialogDefault {
    @Stable
    val paddings = PaddingValues(all = 16.dp)

    @Stable
    val spacings = 8.dp
}

@Stable
object InventoryDialogItemDefault {
    @Stable
    val paddings = PaddingValues(horizontal = 16.dp)

    @Stable
    val spacings = 8.dp
}

@Composable
fun InventoryDialog(
    dialog: State<InventoryDialogUio?>,
    paddings: PaddingValues = InventoryDialogDefault.paddings,
    spacing: Dp = InventoryDialogDefault.spacings,
    onDismissRequest: () -> Unit,
    onItem: (InventoryDialogUio, String) -> Unit,
) {
    LwaDialog(
        state = dialog,
        onDismissRequest = onDismissRequest,
        onConfirm = onDismissRequest,
    ) {
        InventoryDialogContent(
            dialog = it,
            paddings = paddings,
            spacing = spacing,
            onDismissRequest = onDismissRequest,
            onItem = onItem,
        )
    }
}

@Composable
private fun InventoryDialogContent(
    modifier: Modifier = Modifier,
    dialog: InventoryDialogUio,
    paddings: PaddingValues = InventoryDialogDefault.paddings,
    spacing: Dp = InventoryDialogDefault.spacings,
    onDismissRequest: () -> Unit,
    onItem: (InventoryDialogUio, String) -> Unit,
) {
    val layoutDirection = LocalLayoutDirection.current
    val start = remember(layoutDirection) { paddings.calculateStartPadding(layoutDirection) }
    val end = remember(layoutDirection) { paddings.calculateEndPadding(layoutDirection) }
    val top = remember(layoutDirection) { paddings.calculateTopPadding() }
    val bottom = remember(layoutDirection) { paddings.calculateBottomPadding() }

    Column(
        modifier = modifier,
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = top, start = start, bottom = spacing, end = end),
            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 = stringResource(Res.string.character__inventory__inventory__dialog__title),
            )
            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,
                )
            }
        }
        LwaTextField(
            colors = LwaTextFieldColors(backgroundColor = Color.Transparent),
            modifier = Modifier.fillMaxWidth(),
            field = dialog.filter,
            trailingIcon = {
                val value = dialog.filter.valueFlow.collectAsState()
                AnimatedVisibility(
                    visible = value.value.isNotBlank(),
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    IconButton(
                        onClick = { dialog.filter.onValueChange.invoke("") },
                    ) {
                        Icon(
                            painter = painterResource(Res.drawable.ic_cancel_24dp),
                            tint = MaterialTheme.lwa.colorScheme.base.primary,
                            contentDescription = null,
                        )
                    }
                }
            }
        )
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(weight = 1f),
            contentPadding = PaddingValues(
                start = start,
                top = spacing,
                end = end,
                bottom = bottom
            ),
            verticalArrangement = Arrangement.spacedBy(space = spacing),
        ) {
            items(
                items = dialog.items,
                key = { it.itemId },
            ) { item ->
                InventoryDialogItem(
                    modifier = Modifier.animateItem(),
                    item = item,
                    onItem = { onItem(dialog, it) },
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun InventoryDialogItem(
    modifier: Modifier = Modifier,
    paddings: PaddingValues = InventoryDialogItemDefault.paddings,
    spacings: Dp = InventoryDialogItemDefault.spacings,
    item: InventoryDialogUio.Item,
    onItem: (String) -> Unit,
) {
    TooltipLayout(
        modifier = modifier,
        tips = item.tooltips,
        tooltip = { tooltips ->
            DecoratedBox {
                Surface {
                    Box(
                        modifier = Modifier.padding(all = 16.dp)
                    ) {
                        takeIf { tooltips.image?.isNotEmpty() == true }?.let {
                            DesaturatedAsyncImage(
                                modifier = Modifier
                                    .size(96.dp)
                                    .align(alignment = Alignment.TopEnd)
                                    .offset(x = 8.dp, y = (-8).dp),
                                colorFilter = rememberSaturationFilter(),
                                model = tooltips.image,
                                contentScale = ContentScale.Crop,
                                alignment = Alignment.TopCenter,
                                filterQuality = FilterQuality.High,
                                contentDescription = null,
                            )
                        }
                        Column(
                            verticalArrangement = Arrangement.spacedBy(space = 8.dp)
                        ) {
                            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 = { onItem(item.itemId) })
                    .background(color = MaterialTheme.lwa.colorScheme.elevated.base2dp)
                    .minimumInteractiveComponentSize()
                    .padding(paddingValues = paddings)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(space = spacings),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    modifier = Modifier.alignByBaseline(),
                    style = MaterialTheme.lwa.typography.system.body1,
                    fontWeight = FontWeight.Bold,
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1,
                    text = item.label,
                )
            }
        },
    )
}