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

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.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import com.pixelized.desktop.lwa.ui.composable.button.SignButton
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.key.KeyHandler
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.lwa
import com.pixelized.desktop.lwa.utils.extention.onPreviewEscape
import kotlinx.coroutines.flow.StateFlow
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.dialog__cancel_action
import lwacharactersheet.composeapp.generated.resources.dialog__confirm_action
import org.jetbrains.compose.resources.stringResource

@Stable
data class PurseDialogUio(
    val characterSheetId: String,
    val label: StateFlow<String>,
    val add: StateFlow<Boolean>,
    val gold: LwaTextFieldUio,
    val silver: LwaTextFieldUio,
    val copper: LwaTextFieldUio,
    val enableConfirm: StateFlow<Boolean>,
)

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

    @Stable
    val spacings = DpSize(width = 4.dp, height = 8.dp)
}

@Composable
fun PurseDialog(
    dialog: State<PurseDialogUio?>,
    paddings: PaddingValues = PurseDialogDefault.paddings,
    spacings: DpSize = PurseDialogDefault.spacings,
    onConfirm: (PurseDialogUio) -> Unit,
    onSwapSign: (PurseDialogUio) -> Unit,
    onDismissRequest: () -> Unit,
) {
    LwaDialog(
        state = dialog,
        onDismissRequest = onDismissRequest,
        onConfirm = { dialog.value?.let(onConfirm) }
    ) { state ->
        val focusRequester = remember { FocusRequester() }
        LaunchedEffect(Unit) { focusRequester.requestFocus() }

        PurseDialogKeyHandler(
            onSwap = { onSwapSign(state) },
        )

        Column(
            modifier = Modifier.padding(paddingValues = paddings),
            verticalArrangement = Arrangement.spacedBy(space = spacings.height),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            AnimatedContent(
                modifier = Modifier,
                targetState = state.label.collectAsState().value,
                transitionSpec = { fadeIn() togetherWith fadeOut() }
            ) {
                Text(
                    style = MaterialTheme.typography.caption,
                    text = it,
                )
            }
            Row(
                horizontalArrangement = Arrangement.spacedBy(space = spacings.width),
                verticalAlignment = Alignment.Bottom,
            ) {
                SignButton(
                    modifier = Modifier
                        .size(size = 56.dp)
                        .background(
                            color = MaterialTheme.lwa.colorScheme.elevated.base1dp,
                            shape = MaterialTheme.shapes.small,
                        ),
                    add = state.add,
                    onClick = { onSwapSign(state) },
                )
                LwaTextField(
                    modifier = Modifier.focusRequester(focusRequester = focusRequester)
                        .width(100.dp),
                    field = state.gold,
                )
                LwaTextField(
                    modifier = Modifier.width(100.dp),
                    field = state.silver,
                )
                LwaTextField(
                    modifier = Modifier.width(100.dp),
                    field = state.copper,
                )
            }
            Row(
                modifier = Modifier.align(alignment = Alignment.End),
                horizontalArrangement = Arrangement.spacedBy(
                    space = spacings.width,
                    alignment = Alignment.End
                )
            ) {
                TextButton(
                    onClick = onDismissRequest,
                ) {
                    Text(
                        color = MaterialTheme.colors.primary.copy(alpha = .7f),
                        text = stringResource(Res.string.dialog__cancel_action)
                    )
                }
                TextButton(
                    enabled = state.enableConfirm.collectAsState().value,
                    onClick = { onConfirm(state) },
                ) {
                    Text(
                        text = stringResource(Res.string.dialog__confirm_action)
                    )
                }
            }
        }
    }
}

@Composable
private fun PurseContent(
    modifier: Modifier = Modifier,
    dialog: PurseDialogUio,
    onConfirm: (PurseDialogUio) -> Unit,
    onSwapSign: (PurseDialogUio) -> Unit,
    onDismissRequest: () -> Unit,
) {


    Box(
        modifier = Modifier
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = onDismissRequest,
            )
            .onPreviewEscape(
                escape = onDismissRequest,
                enter = { onConfirm(dialog) },
            )
            .fillMaxSize()
            .padding(all = 32.dp),
        contentAlignment = Alignment.Center,
    ) {
        DecoratedBox {
            Surface {

            }
        }
    }
}

@Composable
private fun PurseDialogKeyHandler(
    onSwap: () -> Unit,
) {
    KeyHandler {
        if (it.type == KeyEventType.KeyDown) {
            when (it.key) {
                Key.AltLeft, Key.AltRight -> {
                    onSwap()
                    true
                }

                else -> false
            }
        } else {
            false
        }
    }
}