package com.pixelized.desktop.lwa.ui.screen.admin.item.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.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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
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.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.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.navigation.NavHostController
import com.pixelized.desktop.lwa.ui.composable.checkbox.LwaCheckBox
import com.pixelized.desktop.lwa.ui.composable.checkbox.LwaCheckBoxUio
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.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 com.pixelized.desktop.lwa.utils.extention.calculateHorizontalPaddings
import com.pixelized.desktop.lwa.utils.extention.calculateVerticalPaddings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
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__item__edit_add_alteration
import lwacharactersheet.composeapp.generated.resources.game_master__item__edit_consumable
import lwacharactersheet.composeapp.generated.resources.game_master__item__edit_equipable
import lwacharactersheet.composeapp.generated.resources.game_master__item__edit_stackable
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 GMItemEditPageUio(
    val id: LwaTextFieldUio,
    val label: LwaTextFieldUio,
    val description: LwaTextFieldUio,
    val thumbnail: LwaTextFieldUio,
    val image: LwaTextFieldUio,
    val stackable: LwaCheckBoxUio,
    val equipable: LwaCheckBoxUio,
    val consumable: LwaCheckBoxUio,
    val alterations: StateFlow<List<GMAlterationFieldItemUio>>,
    val tags: MutableStateFlow<List<GMTagUio>>,
)

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

@Composable
fun GMItemEditPage(
    viewModel: GMItemEditViewModel = koinViewModel(),
) {
    val screen = LocalScreenController.current
    val focus = LocalFocusManager.current
    val scope = rememberCoroutineScope()

    val form = viewModel.form.collectAsState()

    GMItemEditContent(
        modifier = Modifier.fillMaxSize(),
        form = form,
        onBack = {
            focus.clearFocus(force = true)
            screen.navigateBack()
        },
        onSave = {
            focus.clearFocus(force = true)
            scope.launch {
                if (viewModel.save()) {
                    screen.navigateBack()
                }
            }
        },
        onAddAlteration = {
            focus.clearFocus(force = true)
            viewModel.addAlteration()
        },
        onAlteration = { field, selected ->
            focus.clearFocus(force = true)
            viewModel.toggleAlteration(
                field = field,
                selected = selected,
            )
        },
        onRemoveAlteration = {
            focus.clearFocus(force = true)
            viewModel.removeAlteration(key = it)
        },
        onTag = { tag ->
            focus.clearFocus(force = true)
            viewModel.addTag(tag = tag)
        },
    )

    ErrorSnackHandler(
        error = viewModel.error,
    )

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

@Composable
private fun GMItemEditContent(
    modifier: Modifier = Modifier,
    scope: CoroutineScope = rememberCoroutineScope(),
    tagsState: LazyListState = rememberLazyListState(),
    form: State<GMItemEditPageUio?>,
    paddings: PaddingValues = GMItemEditDefault.paddings,
    onBack: () -> Unit,
    onSave: () -> Unit,
    onAddAlteration: () -> Unit,
    onAlteration: (GMAlterationFieldItemUio, GMAlterationFieldItemUio.Field?) -> Unit,
    onRemoveAlteration: (String) -> Unit,
    onTag: (GMTagUio) -> 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 -> {
                        val tags = it.tags.collectAsState()
                        val alterations = it.alterations.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 = "Image") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.image,
                                    singleLine = true,
                                )
                            }
                            item(key = "Thumbnail") {
                                LwaTextField(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = it.thumbnail,
                                    singleLine = true,
                                )
                            }
                            item(key = "Stackable") {
                                Row(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding)
                                        .padding(start = 16.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Text(
                                        style = MaterialTheme.lwa.typography.system.body1,
                                        text = stringResource(Res.string.game_master__item__edit_stackable)
                                    )
                                    LwaCheckBox(
                                        field = it.stackable,
                                    )
                                }
                            }
                            item(key = "Equipable") {
                                Row(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding)
                                        .padding(start = 16.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Text(
                                        style = MaterialTheme.lwa.typography.system.body1,
                                        text = stringResource(Res.string.game_master__item__edit_equipable)
                                    )
                                    LwaCheckBox(
                                        field = it.equipable,
                                    )
                                }
                            }
                            item(key = "Consumable") {
                                Row(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding)
                                        .padding(start = 16.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Text(
                                        style = MaterialTheme.lwa.typography.system.body1,
                                        text = stringResource(Res.string.game_master__item__edit_consumable)
                                    )
                                    LwaCheckBox(
                                        field = it.consumable,
                                    )
                                }
                            }
                            item(key = "Tags") {
                                LazyRow(
                                    modifier = Modifier.draggable(
                                        orientation = Orientation.Horizontal,
                                        state = rememberDraggableState { delta ->
                                            scope.launch {
                                                tagsState.scrollBy(-delta)
                                            }
                                        },
                                    ),
                                    contentPadding = horizontalPadding,
                                    state = tagsState,
                                    horizontalArrangement = Arrangement.spacedBy(space = 8.dp),
                                ) {
                                    items(
                                        items = tags.value,
                                    ) { tag ->
                                        GMTagButton(
                                            modifier = Modifier.height(48.dp),
                                            tag = tag,
                                            onTag = { onTag(tag) }
                                        )
                                    }
                                }
                            }
                            items(
                                items = alterations.value,
                                key = { field -> field.key },
                            ) { field ->
                                GMAlterationFieldItem(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    field = field,
                                    onAlteration = { alterationId ->
                                        onAlteration(field, alterationId)
                                    },
                                    onRemoveField = onRemoveAlteration,
                                )
                            }
                            item(key = "Actions") {
                                Column(
                                    modifier = Modifier
                                        .animateItem()
                                        .fillMaxWidth()
                                        .padding(paddingValues = horizontalPadding),
                                    horizontalAlignment = Alignment.End
                                ) {
                                    Button(
                                        colors = LwaButtonColors(),
                                        shape = CircleShape,
                                        onClick = onAddAlteration,
                                    ) {
                                        Text(
                                            modifier = Modifier.padding(end = 4.dp),
                                            text = stringResource(Res.string.game_master__item__edit_add_alteration),
                                        )
                                        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 ItemEditKeyHandler(
    onDismissRequest: () -> Unit,
) {
    KeyHandler {
        when {
            it.type == KeyEventType.KeyDown && it.key == Key.Escape -> {
                onDismissRequest()
                true
            }

            else -> false
        }
    }
}

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