package com.pixelized.desktop.lwa.ui.screen.admin.map.edit

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.pixelized.desktop.lwa.ui.composable.error.ErrorSnackHandler
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.navigation.screen.LocalScreenController
import com.pixelized.desktop.lwa.ui.navigation.screen.destination.gamemaster.GMItemEditDestination
import com.pixelized.desktop.lwa.ui.navigation.screen.destination.gamemaster.GMMapEditDestination
import com.pixelized.desktop.lwa.ui.theme.color.component.LwaButtonColors
import com.pixelized.desktop.lwa.ui.theme.lwa
import com.pixelized.desktop.lwa.utils.extention.calculateHorizontalPaddings
import com.pixelized.desktop.lwa.utils.extention.calculateVerticalPaddings
import kotlinx.coroutines.launch
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.game_master__action__save
import lwacharactersheet.composeapp.generated.resources.game_master__item__create
import lwacharactersheet.composeapp.generated.resources.game_master__map__edit_camera_label
import lwacharactersheet.composeapp.generated.resources.game_master__map__edit_size_label
import lwacharactersheet.composeapp.generated.resources.game_master__map__layer_layer_label
import lwacharactersheet.composeapp.generated.resources.game_master__map__layer_root_label
import lwacharactersheet.composeapp.generated.resources.ic_save_24dp
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel

@Stable
data class GMMapEditPageUio(
    val id: LwaTextFieldUio,
    val label: LwaTextFieldUio,
    val cameraZoom: LwaTextFieldUio,
    val cameraOffsetX: LwaTextFieldUio,
    val cameraOffsetY: LwaTextFieldUio,
    val sizeWidth: LwaTextFieldUio,
    val sizeHeight: LwaTextFieldUio,
    val rootId: LwaTextFieldUio,
    val rootName: LwaTextFieldUio,
    val rootUri: LwaTextFieldUio,
    val layerId: LwaTextFieldUio,
    val layerName: LwaTextFieldUio,
    val layerUri: LwaTextFieldUio,
)

@Stable
object GMMapEditDefault {
    val paddings = PaddingValues(all = 8.dp)

    val spacing = 8.dp
}

@Composable
fun GMMapEditPage(
    viewModel: GMMapEditViewModel = koinViewModel(),
    paddings: PaddingValues = GMMapEditDefault.paddings,
) {
    val screen = LocalScreenController.current
    val focus = LocalFocusManager.current
    val scope = rememberCoroutineScope()

    val form = viewModel.form.collectAsState()

    GMItemEditContent(
        modifier = Modifier.fillMaxSize(),
        paddings = paddings,
        form = form,
        onBack = {
            focus.clearFocus(force = true)
            screen.navigateBack()
        },
        onSave = {
            focus.clearFocus(force = true)
            scope.launch {
                if (viewModel.save()) {
                    screen.navigateBack()
                }
            }
        },
    )

    ErrorSnackHandler(
        error = viewModel.error,
    )

    ItemEditKeyHandler(
        onDismissRequest = {
            screen.navigateBack()
        },
    )
}

@Composable
private fun GMItemEditContent(
    modifier: Modifier = Modifier,
    paddings: PaddingValues = GMMapEditDefault.paddings,
    spacing: Dp = GMMapEditDefault.spacing,
    form: State<GMMapEditPageUio?>,
    onBack: () -> Unit,
    onSave: () -> Unit,
) {
    val verticalPadding = paddings.calculateVerticalPaddings()
    val horizontalPadding = paddings.calculateHorizontalPaddings()

    Scaffold(
        modifier = modifier,
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = stringResource(Res.string.game_master__item__create),
                    )
                },
                navigationIcon = {
                    IconButton(
                        onClick = onBack,
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Default.ArrowBack,
                            contentDescription = null,
                        )
                    }
                },
                actions = {
                    TextButton(
                        onClick = onSave,
                    ) {
                        Text(
                            modifier = Modifier.padding(end = 4.dp),
                            color = MaterialTheme.lwa.colorScheme.base.primary,
                            fontWeight = FontWeight.SemiBold,
                            text = stringResource(Res.string.game_master__action__save),
                        )
                        Icon(
                            painter = painterResource(Res.drawable.ic_save_24dp),
                            tint = MaterialTheme.lwa.colorScheme.base.primary,
                            contentDescription = null,
                        )
                    }
                }
            )
        },
        content = {
            AnimatedContent(
                targetState = form.value,
                transitionSpec = {
                    if (initialState?.id == targetState?.id) {
                        EnterTransition.None togetherWith ExitTransition.None
                    } else {
                        fadeIn() togetherWith fadeOut()
                    }
                }
            ) {
                when (it) {
                    null -> Box(
                        modifier = Modifier.fillMaxSize(),
                    )

                    else -> {
                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = verticalPadding,
                            verticalArrangement = Arrangement.spacedBy(space = spacing),
                        ) {
                            item(key = "Id") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.id,
                                    singleLine = true,
                                )
                            }
                            item(key = "Name") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.label,
                                    singleLine = true,
                                )
                            }
                            item(key = "Camera") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    verticalArrangement = Arrangement.spacedBy(space = spacing),
                                ) {
                                    Text(
                                        style = MaterialTheme.typography.caption,
                                        text = stringResource(Res.string.game_master__map__edit_camera_label)
                                    )
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(space = spacing),
                                    ) {
                                        LwaTextField(
                                            modifier = Modifier.weight(1f),
                                            field = it.cameraZoom,
                                            singleLine = true,
                                        )
                                        LwaTextField(
                                            modifier = Modifier.weight(1f),
                                            field = it.cameraOffsetX,
                                            singleLine = true,
                                        )
                                        LwaTextField(
                                            modifier = Modifier.weight(1f),
                                            field = it.cameraOffsetY,
                                            singleLine = true,
                                        )
                                    }
                                }
                            }
                            item(key = "Size") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                ) {
                                    Text(
                                        style = MaterialTheme.typography.caption,
                                        text = stringResource(Res.string.game_master__map__edit_size_label)
                                    )
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(space = spacing),
                                    ) {
                                        LwaTextField(
                                            modifier = Modifier.weight(1f),
                                            field = it.sizeWidth,
                                            singleLine = true,
                                        )
                                        LwaTextField(
                                            modifier = Modifier.weight(1f),
                                            field = it.sizeHeight,
                                            singleLine = true,
                                        )
                                    }
                                }
                            }
                            item(key = "Background") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    verticalArrangement = Arrangement.spacedBy(space = spacing),
                                ) {
                                    Text(
                                        style = MaterialTheme.typography.caption,
                                        text = stringResource(Res.string.game_master__map__layer_root_label)
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.rootId,
                                        singleLine = true,
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.rootName,
                                        singleLine = true,
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.rootUri,
                                        singleLine = true,
                                    )
                                }
                            }
                            item(key = "Layer") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    verticalArrangement = Arrangement.spacedBy(space = spacing),
                                ) {
                                    Text(
                                        style = MaterialTheme.typography.caption,
                                        text = stringResource(Res.string.game_master__map__layer_layer_label)
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.layerId,
                                        singleLine = true,
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.layerName,
                                        singleLine = true,
                                    )
                                    LwaTextField(
                                        modifier = Modifier.fillMaxWidth(),
                                        field = it.layerUri,
                                        singleLine = true,
                                    )
                                }
                            }
                            item(key = "Actions") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    horizontalAlignment = Alignment.End
                                ) {
                                    Button(
                                        colors = LwaButtonColors(),
                                        shape = CircleShape,
                                        onClick = onSave,
                                    ) {
                                        Text(
                                            modifier = Modifier.padding(end = 4.dp),
                                            text = stringResource(Res.string.game_master__action__save),
                                        )
                                        Icon(
                                            painter = painterResource(Res.drawable.ic_save_24dp),
                                            contentDescription = null,
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    )
}

@Composable
private fun ItemEditKeyHandler(
    onDismissRequest: () -> Unit,
) {
    KeyHandler {
        when {
            it.type == KeyEventType.KeyDown && it.key == Key.Escape -> {
                onDismissRequest()
                true
            }

            else -> false
        }
    }
}

private fun NavHostController.navigateBack() = popBackStack(
    route = GMMapEditDestination.baseRoute(),
    inclusive = true,
)
