package com.pixelized.desktop.lwa.ui.screen.admin.alteration.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.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.gestures.scrollBy
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
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.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
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.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.LocalLayoutDirection
import androidx.compose.ui.text.font.FontWeight
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.GMAlterationEditDestination
import com.pixelized.desktop.lwa.ui.screen.admin.common.tag.GMTagButton
import com.pixelized.desktop.lwa.ui.screen.admin.common.tag.GMTagUio
import com.pixelized.desktop.lwa.ui.theme.color.component.LwaButtonColors
import com.pixelized.desktop.lwa.ui.theme.lwa
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
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__alteration__edit_add_field
import lwacharactersheet.composeapp.generated.resources.game_master__alteration__title
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 GMAlterationEditPageUio(
    val id: LwaTextFieldUio,
    val label: LwaTextFieldUio,
    val description: LwaTextFieldUio,
    val icon: LwaTextFieldUio,
    val tags: MutableStateFlow<List<GMTagUio>>,
    val fields: MutableStateFlow<List<SkillUio>>,
) {
    @Stable
    data class SkillUio(
        val key: String,
        val id: LwaTextFieldUio,
        val expression: LwaTextFieldUio,
    )
}

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

@Composable
fun GMAlterationEditScreen(
    viewModel: GMAlterationEditViewModel = koinViewModel(),
) {
    val screen = LocalScreenController.current
    val scope = rememberCoroutineScope()

    val form = viewModel.form.collectAsState()

    GMAlterationEditContent(
        modifier = Modifier.fillMaxSize(),
        form = form,
        onBack = {
            screen.navigateBack()
        },
        addField = {
            scope.launch {
                viewModel.addField()
            }
        },
        removeField = viewModel::removeField,
        onSave = {
            scope.launch {
                if (viewModel.save()) {
                    screen.navigateBack()
                }
            }
        },
        onTag = { tag ->
            viewModel.addTag(tag = tag)
        },
    )

    ErrorSnackHandler(
        error = viewModel.error,
    )

    AlterationEditKeyHandler(
        onDismissRequest = {
            screen.navigateBack()
        }
    )
}

@Composable
private fun GMAlterationEditContent(
    modifier: Modifier = Modifier,
    paddings: PaddingValues = GMAlterationEditPageDefault.paddings,
    scope: CoroutineScope = rememberCoroutineScope(),
    tagsState: LazyListState = rememberLazyListState(),
    form: State<GMAlterationEditPageUio?>,
    onBack: () -> Unit,
    addField: () -> Unit,
    removeField: (index: Int) -> Unit,
    onSave: () -> Unit,
    onTag: (GMTagUio) -> Unit,
) {
    val layoutDirection = LocalLayoutDirection.current
    val verticalPadding = remember(paddings) {
        PaddingValues(
            top = paddings.calculateTopPadding(),
            bottom = paddings.calculateBottomPadding(),
        )
    }
    val horizontalPadding = remember(paddings, layoutDirection) {
        PaddingValues(
            start = paddings.calculateStartPadding(layoutDirection = layoutDirection),
            end = paddings.calculateEndPadding(layoutDirection = layoutDirection),
        )
    }

    Scaffold(
        modifier = modifier,
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = stringResource(Res.string.game_master__alteration__title),
                    )
                },
                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 -> {
                        val tags = it.tags.collectAsState()
                        val fields = it.fields.collectAsState()

                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = verticalPadding,
                            verticalArrangement = Arrangement.spacedBy(space = 8.dp),
                        ) {
                            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 = "Description") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.description,
                                    singleLine = false,
                                )
                            }
                            item(key = "Icon") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.icon,
                                    singleLine = false,
                                )
                            }
                            item(key = "Tags") {
                                LazyRow(
                                    modifier = Modifier.draggable(
                                        orientation = Orientation.Horizontal,
                                        state = rememberDraggableState { delta ->
                                            scope.launch {
                                                tagsState.scrollBy(-delta)
                                            }
                                        },
                                    ),
                                    state = tagsState,
                                    contentPadding = horizontalPadding,
                                    horizontalArrangement = Arrangement.spacedBy(space = 8.dp),
                                ) {
                                    items(
                                        items = tags.value,
                                    ) { tag ->
                                        GMTagButton(
                                            modifier = Modifier.height(48.dp),
                                            tag = tag,
                                            onTag = { onTag(tag) }
                                        )
                                    }
                                }
                            }
                            itemsIndexed(
                                items = fields.value,
                                key = { _, item -> item.key },
                            ) { index, item ->
                                Row(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    horizontalArrangement = Arrangement.spacedBy(space = 8.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    LwaTextField(
                                        modifier = Modifier.weight(1f),
                                        field = item.id,
                                        singleLine = true,
                                    )
                                    LwaTextField(
                                        modifier = Modifier.weight(1f),
                                        field = item.expression,
                                        singleLine = true,
                                    )
                                    IconButton(
                                        modifier = Modifier
                                            .size(size = 56.dp)
                                            .background(
                                                color = MaterialTheme.lwa.colorScheme.elevated.base1dp,
                                                shape = MaterialTheme.shapes.small,
                                            ),
                                        onClick = { removeField(index) },
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Close,
                                            tint = MaterialTheme.lwa.colorScheme.base.primary,
                                            contentDescription = null,
                                        )
                                    }
                                }
                            }
                            item(key = "Actions") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    horizontalAlignment = Alignment.End
                                ) {
                                    Button(
                                        colors = LwaButtonColors(),
                                        shape = CircleShape,
                                        onClick = addField,
                                    ) {
                                        Text(
                                            modifier = Modifier.padding(end = 4.dp),
                                            text = stringResource(Res.string.game_master__alteration__edit_add_field),
                                        )
                                        Icon(
                                            imageVector = Icons.Default.Add,
                                            contentDescription = null,
                                        )
                                    }
                                    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 AlterationEditKeyHandler(
    onDismissRequest: () -> Unit,
) {
    KeyHandler {
        when {
            it.type == KeyEventType.KeyDown && it.key == Key.Escape -> {
                onDismissRequest()
                true
            }

            else -> false
        }
    }
}

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