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

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkHorizontally
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.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.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.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
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.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.LocalFocusManager
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.DpSize
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.GMCharacterEditDestination
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.dialog.GMCharacterSheetCopyDialog
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.dialog.GMCharacterSheetCopyDialogViewModel
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.item.GMActionField
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.item.GMActionFieldUio
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.item.GMSkillField
import com.pixelized.desktop.lwa.ui.screen.admin.character.edit.item.GMSkillFieldUio
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.lwa
import com.pixelized.desktop.lwa.utils.extention.unpack
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__action__save_as
import lwacharactersheet.composeapp.generated.resources.game_master__character_edit__title
import lwacharactersheet.composeapp.generated.resources.ic_save_24dp
import lwacharactersheet.composeapp.generated.resources.ic_save_as_24dp
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel

@Stable
data class GMCharacterEditPageUio(
    val characterSheetId: LwaTextFieldUio,
    val name: LwaTextFieldUio,
    val job: LwaTextFieldUio,
    val portrait: LwaTextFieldUio,
    val thumbnail: LwaTextFieldUio,
    val externalLink: LwaTextFieldUio,
    val level: LwaTextFieldUio,
    val levelUp: LwaCheckBoxUio,
    val characteristics: CharacteristicsUio,
    val tags: MutableStateFlow<List<GMTagUio>>,
    val commonSkills: List<GMSkillFieldUio>,
    val specialSkills: List<GMSkillFieldUio>,
    val magicSkills: List<GMSkillFieldUio>,
    val actions: List<GMActionFieldUio>,
) {
    @Stable
    data class CharacteristicsUio(
        val strength: LwaTextFieldUio,
        val dexterity: LwaTextFieldUio,
        val constitution: LwaTextFieldUio,
        val height: LwaTextFieldUio,
        val intelligence: LwaTextFieldUio,
        val power: LwaTextFieldUio,
        val charisma: LwaTextFieldUio,
    ) {
        val values =
            listOf(strength, dexterity, constitution, height, intelligence, power, charisma)
    }
}

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

    @Stable
    val spacing: DpSize = DpSize(8.dp, 8.dp)
}

@Composable
fun GMCharacterEditPage(
    viewModel: GMCharacterEditViewModel = koinViewModel(),
    copyViewModel: GMCharacterSheetCopyDialogViewModel = koinViewModel(),
) {
    val focus = LocalFocusManager.current // focus cause a lot of issues with animateItem
    val screen = LocalScreenController.current
    val scope = rememberCoroutineScope()
    val formState = rememberLazyListState()
    val tagsState = rememberLazyListState()

    val form = viewModel.form.collectAsState()

    GMCharacterEditContent(
        modifier = Modifier.fillMaxSize(),
        formState = formState,
        tagsState = tagsState,
        page = form,
        onBack = {
            screen.navigateBack()
        },
        onSave = {
            scope.launch {
                if (viewModel.save()) {
                    screen.navigateBack()
                }
            }
        },
        onSaveAs = {
            scope.launch {
                copyViewModel.showCharacterSheetCopyDialog(
                    characterSheetId = form.value?.characterSheetId?.valueFlow?.value,
                    characterName = form.value?.name?.valueFlow?.value,
                )
            }
        },
        onTag = { tag ->
            viewModel.addTag(tag = tag)
        },
        onSpecialSkillAdd = {
            focus.clearFocus(force = true)
            scope.launch { viewModel.addSpecialSkill() }
        },
        onSpecialSkillDelete = { index ->
            focus.clearFocus(force = true)
            scope.launch { viewModel.deleteSpecialSkill(index = index) }
        },
        onMagicSkillAdd = {
            focus.clearFocus(force = true)
            scope.launch { viewModel.addMagicSkill() }
        },
        onMagicSkillDelete = { index ->
            focus.clearFocus(force = true)
            scope.launch { viewModel.deleteMagicSkill(index = index) }
        },
        onActionAdd = {
            focus.clearFocus(force = true)
            scope.launch { viewModel.addAction() }
        },
        onActionDelete = { index ->
            focus.clearFocus(force = true)
            scope.launch { viewModel.deleteAction(index = index) }
        },
        onSkillOccupation = { skill ->
            focus.clearFocus(force = true)
            viewModel.toggleOccupation(skillId = skill.id.valueFlow.value)
        }
    )

    GMCharacterSheetCopyDialog(
        dialog = copyViewModel.dialog.collectAsState(),
        onDismissRequest = {
            scope.launch { copyViewModel.hideCharacterSheetCopyDialog() }
        },
        onConfirm = { dialog ->
            scope.launch {
                if (copyViewModel.isValid()) {
                    if (viewModel.saveAs(
                            overrideCharacterSheetId = dialog.id.unpack<String>(),
                            overrideCharacterName = dialog.name.unpack<String>(),
                        )
                    ) {
                        screen.navigateBack()
                    }
                }
            }
        },
    )

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

    ErrorSnackHandler(
        error = copyViewModel.error,
    )

    ErrorSnackHandler(
        error = viewModel.error,
    )
}

@Composable
fun GMCharacterEditContent(
    modifier: Modifier = Modifier,
    paddings: PaddingValues = GMCharacterEditPageDefault.paddings,
    spacing: DpSize = GMCharacterEditPageDefault.spacing,
    scope: CoroutineScope = rememberCoroutineScope(),
    formState: LazyListState = rememberLazyListState(),
    tagsState: LazyListState = rememberLazyListState(),
    page: State<GMCharacterEditPageUio?>,
    onBack: () -> Unit,
    onSaveAs: () -> Unit,
    onSave: () -> Unit,
    onTag: (GMTagUio) -> Unit,
    onSpecialSkillAdd: () -> Unit,
    onSpecialSkillDelete: (Int) -> Unit,
    onMagicSkillAdd: () -> Unit,
    onMagicSkillDelete: (Int) -> Unit,
    onActionAdd: () -> Unit,
    onActionDelete: (Int) -> Unit,
    onSkillOccupation: (GMSkillFieldUio) -> 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__character_edit__title),
                    )
                },
                navigationIcon = {
                    IconButton(
                        onClick = onBack,
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Default.ArrowBack,
                            contentDescription = null,
                        )
                    }
                },
                actions = {
                    val saveAsHover = remember { MutableInteractionSource() }
                    TextButton(
                        modifier = Modifier.hoverable(interactionSource = saveAsHover),
                        onClick = onSaveAs,
                    ) {
                        AnimatedVisibility(
                            visible = saveAsHover.collectIsHoveredAsState().value,
                            enter = fadeIn() + expandHorizontally(),
                            exit = fadeOut() + shrinkHorizontally(),
                        ) {
                            Text(
                                modifier = Modifier.padding(end = spacing.width),
                                color = MaterialTheme.lwa.colorScheme.base.primary,
                                fontWeight = FontWeight.SemiBold,
                                text = stringResource(Res.string.game_master__action__save_as),
                            )
                        }
                        Icon(
                            painter = painterResource(Res.drawable.ic_save_as_24dp),
                            tint = MaterialTheme.lwa.colorScheme.base.primary,
                            contentDescription = null,
                        )
                    }
                    TextButton(
                        onClick = onSave,
                    ) {
                        AnimatedVisibility(
                            visible = saveAsHover.collectIsHoveredAsState().value.not(),
                            enter = fadeIn() + expandHorizontally(),
                            exit = fadeOut() + shrinkHorizontally(),
                        ) {
                            Text(
                                modifier = Modifier.padding(end = spacing.width),
                                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 = {
            when (val form = page.value) {
                null -> Box(
                    modifier = Modifier.fillMaxSize(),
                )

                else -> {
                    val tags = form.tags.collectAsState()

                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = verticalPadding,
                        state = formState,
                        verticalArrangement = Arrangement.spacedBy(space = spacing.height),
                    ) {
                        item(key = "MetadataTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Metadata",
                            )
                        }
                        item(key = "characterSheetId") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.characterSheetId,
                                singleLine = true,
                            )
                        }
                        item(key = "name") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.name,
                                singleLine = true,
                            )
                        }
                        item(key = "job") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.job,
                                singleLine = true,
                            )
                        }
                        item(key = "portrait") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.portrait,
                                singleLine = true,
                            )
                        }
                        item(key = "thumbnail") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.thumbnail,
                                singleLine = true,
                            )
                        }
                        item(key = "external") {
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = form.externalLink,
                                singleLine = true,
                            )
                        }
                        item(key = "Level") {
                            Row(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(space = spacing.width),
                            ) {
                                LwaTextField(
                                    modifier = Modifier.weight(weight = 1f),
                                    field = form.level,
                                    singleLine = true,
                                )
                                Row(
                                    modifier = Modifier.weight(weight = 1f),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    LwaCheckBox(
                                        field = form.levelUp,
                                    )
                                    Text(
                                        style = MaterialTheme.lwa.typography.system.body1,
                                        overflow = TextOverflow.Ellipsis,
                                        maxLines = 1,
                                        text = "Montée de niveau"
                                    )
                                }
                            }
                        }
                        item(key = "tags") {
                            LazyRow(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .draggable(
                                        orientation = Orientation.Horizontal,
                                        state = rememberDraggableState { delta ->
                                            scope.launch {
                                                tagsState.scrollBy(-delta)
                                            }
                                        },
                                    ),
                                state = tagsState,
                                contentPadding = horizontalPadding,
                            ) {
                                items(
                                    items = tags.value,
                                    key = { tag -> tag.id },
                                ) { tag ->
                                    GMTagButton(
                                        tag = tag,
                                        onTag = { onTag(tag) },
                                    )
                                }
                            }
                        }
                        item(key = "CharacteristicsTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(paddingValues = horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Characteristics",
                            )
                        }
                        items(
                            items = form.characteristics.values,
                            key = { "characteristics-${it.labelFlow}" },
                        ) { characteristic ->
                            LwaTextField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                field = characteristic,
                                singleLine = true,
                            )
                        }
                        item(key = "CommonSkillsTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(paddingValues = horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Compétences communes",
                            )
                        }
                        items(
                            items = form.commonSkills,
                            key = { item -> item.key },
                        ) { item ->
                            GMSkillField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                skill = item,
                                onDelete = null,
                                onOccupation = onSkillOccupation,
                            )
                        }
                        item(key = "SpecialSkillsTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(paddingValues = horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Compétences spéciales",
                            )
                        }
                        itemsIndexed(
                            items = form.specialSkills,
                            key = { _, item -> item.key },
                        ) { index, item ->
                            GMSkillField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                skill = item,
                                onDelete = { onSpecialSkillDelete(index) },
                                onOccupation = onSkillOccupation,
                            )
                        }
                        item(key = "SpecialSkillsAdd") {
                            Row(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                horizontalArrangement = Arrangement.End
                            ) {
                                TextButton(
                                    onClick = onSpecialSkillAdd,
                                ) {
                                    Text(text = "Ajouter une compétence spéciale")
                                }
                            }
                        }
                        item(key = "MagicSkillsTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(paddingValues = horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Compétences magiques",
                            )
                        }
                        itemsIndexed(
                            items = form.magicSkills,
                            key = { _, item -> item.key },
                        ) { index, item ->
                            GMSkillField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                skill = item,
                                onDelete = { onMagicSkillDelete(index) },
                                onOccupation = onSkillOccupation,
                            )
                        }
                        item(key = "MagicSkillsAdd") {
                            Row(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                horizontalArrangement = Arrangement.End
                            ) {
                                TextButton(
                                    onClick = onMagicSkillAdd,
                                ) {
                                    Text(text = "Ajouter une compétence magique")
                                }
                            }
                        }
                        item(key = "ActionsTitle") {
                            Text(
                                modifier = Modifier
                                    .animateItem()
                                    .padding(paddingValues = horizontalPadding),
                                style = MaterialTheme.lwa.typography.system.caption,
                                text = "Actions",
                            )
                        }
                        itemsIndexed(
                            items = form.actions,
                            key = { _, item -> item.id },
                        ) { index, item ->
                            GMActionField(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                action = item,
                                onDelete = { onActionDelete(index) }
                            )
                        }
                        item(key = "ActionAdd") {
                            Row(
                                modifier = Modifier
                                    .animateItem()
                                    .fillMaxWidth()
                                    .padding(paddingValues = horizontalPadding),
                                horizontalArrangement = Arrangement.End
                            ) {
                                TextButton(
                                    onClick = onActionAdd,
                                ) {
                                    Text(text = "Ajouter une action")
                                }
                            }
                        }
                    }
                }
            }
        },
    )
}


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

            else -> false
        }
    }
}

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