package com.pixelized.desktop.lwa.ui.screen.levelup

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ScrollState
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.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.Shape
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.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.pixelized.desktop.lwa.LocalRollHostState
import com.pixelized.desktop.lwa.ui.composable.decoratedBox.DecoratedBox
import com.pixelized.desktop.lwa.ui.composable.image.LwaAsyncImage
import com.pixelized.desktop.lwa.ui.composable.key.KeyHandler
import com.pixelized.desktop.lwa.ui.navigation.screen.LocalScreenController
import com.pixelized.desktop.lwa.ui.navigation.screen.destination.LevelUpDestination
import com.pixelized.desktop.lwa.ui.overlay.roll.RollResult
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpCharacteristic
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpCharacteristicUio
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpSkill
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpSkillUio
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpSubCharacteristic
import com.pixelized.desktop.lwa.ui.screen.levelup.items.LevelUpSubCharacteristicUio
import com.pixelized.desktop.lwa.ui.theme.lwa
import kotlinx.coroutines.launch
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character_sheet__skills__common_title
import lwacharactersheet.composeapp.generated.resources.character_sheet__skills__magic_title
import lwacharactersheet.composeapp.generated.resources.character_sheet__skills__special_title
import lwacharactersheet.composeapp.generated.resources.level_up__action
import lwacharactersheet.composeapp.generated.resources.level_up__character__label
import lwacharactersheet.composeapp.generated.resources.level_up__title
import org.jetbrains.compose.resources.StringResource
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel

@Stable
data class LevelUpHeaderUio(
    val name: String,
    val level: Int,
    val portrait: String?,
    val hp: LevelUpSubCharacteristicUio,
    val pp: LevelUpSubCharacteristicUio,
    val bonus: LevelUpSubCharacteristicUio,
    val grow: LevelUpSubCharacteristicUio,
    val learn: LevelUpSubCharacteristicUio,
)

@Stable
data class LevelUpSectionUio(
    val commonSkills: List<LevelUpSkillUio>?,
    val specialSkills: List<LevelUpSkillUio>?,
    val magicSkills: List<LevelUpSkillUio>?,
)

@Composable
fun LevelUpScreen(
    viewModel: LevelUpViewModel = koinViewModel(),
) {
    val screen = LocalScreenController.current
    val roll = LocalRollHostState.current
    val scope = rememberCoroutineScope()

    val header = viewModel.header.collectAsState()
    val characteristics = viewModel.characteristics.collectAsState()
    val skills = viewModel.skills.collectAsState()
    val commitLevelUp = viewModel.displayCommitLevelUp.collectAsState()

    Surface {
        LevelUpContent(
            modifier = Modifier.fillMaxSize(),
            commitLevelUp = commitLevelUp,
            header = header,
            characteristics = characteristics,
            skills = skills,
            onBack = {
                screen.navigateBack()
            },
            onCommitLevelUp = {
                scope.launch {
                    viewModel.commitLevelUp()
                    screen.navigateBack()
                }
            },
            onCharacteristic = {
                viewModel.selectCharacteristic(it.characteristicId)
            },
            onSkill = {
                scope.launch {
                    if (it.roll != null) {
                        val result: RollResult = roll.showRollOverlay(roll = it.roll)
                        viewModel.applyRollResult(skillId = it.skillId, result = result)
                    }
                }
            },
        )
    }

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

@Composable
private fun LevelUpContent(
    modifier: Modifier = Modifier,
    scrollState: ScrollState = rememberScrollState(),
    lazyListState: LazyListState = rememberLazyListState(),
    commitLevelUp: State<Boolean>,
    header: State<LevelUpHeaderUio?>,
    characteristics: State<List<LevelUpCharacteristicUio>>,
    skills: State<LevelUpSectionUio?>,
    onBack: () -> Unit,
    onCommitLevelUp: () -> Unit,
    onCharacteristic: (LevelUpCharacteristicUio) -> Unit,
    onSkill: (LevelUpSkillUio) -> Unit,
) {
    val scope = rememberCoroutineScope()

    LevelUpLayout(
        modifier = modifier,
        topBar = {
            TopAppBar(
                title = {
                    Text(text = stringResource(Res.string.level_up__title))
                },
                navigationIcon = {
                    IconButton(
                        onClick = onBack,
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Default.ArrowBack,
                            contentDescription = null,
                        )
                    }
                },
                actions = {
                    AnimatedVisibility(
                        visible = commitLevelUp.value,
                        enter = fadeIn(),
                        exit = fadeOut(),
                    ) {
                        TextButton(
                            onClick = onCommitLevelUp,
                        ) {
                            Text(text = stringResource(Res.string.level_up__action))
                        }
                    }
                },
            )
        },
        background = {
            LwaAsyncImage(
                modifier = Modifier.matchParentSize(),
                model = header.value?.portrait,
                contentScale = ContentScale.FillHeight,
                alignment = Alignment.Center,
                filterQuality = FilterQuality.High,
                contentDescription = null,
            )
        },
        panel = {
            Column(
                modifier = Modifier
                    .matchParentSize()
                    .background(color = MaterialTheme.lwa.colorScheme.elevated.base1dp),
                verticalArrangement = Arrangement.spacedBy(space = 8.dp),
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(color = MaterialTheme.lwa.colorScheme.elevated.base2dp)
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    verticalArrangement = Arrangement.spacedBy(space = 8.dp),
                ) {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(space = 4.dp),
                    ) {
                        Text(
                            modifier = Modifier.alignByBaseline(),
                            style = MaterialTheme.typography.h5,
                            text = header.value?.name ?: "",
                            overflow = TextOverflow.Ellipsis,
                            maxLines = 1,
                        )
                        Text(
                            modifier = Modifier.alignByBaseline(),
                            style = MaterialTheme.lwa.typography.system.caption,
                            text = (header.value?.level ?: 0).let { level ->
                                stringResource(
                                    resource = Res.string.level_up__character__label,
                                    level, level + 1
                                )
                            },
                        )
                    }
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(space = 16.dp),
                    ) {
                        LevelUpSubCharacteristic(
                            characteristic = header.value?.hp,
                        )
                        LevelUpSubCharacteristic(
                            characteristic = header.value?.pp,
                        )
                        Spacer(
                            modifier = Modifier.weight(weight = 1f)
                        )
                        LevelUpSubCharacteristic(
                            characteristic = header.value?.bonus,
                        )
                        LevelUpSubCharacteristic(
                            characteristic = header.value?.grow,
                        )
                        LevelUpSubCharacteristic(
                            characteristic = header.value?.learn,
                        )
                    }
                }
                Column(
                    modifier = Modifier.verticalScroll(state = scrollState),
                ) {
                    LazyRow(
                        modifier = Modifier.draggable(
                            orientation = Orientation.Horizontal,
                            state = rememberDraggableState { delta ->
                                scope.launch {
                                    lazyListState.scrollBy(-delta)
                                }
                            },
                        ),
                        state = lazyListState,
                        contentPadding = PaddingValues(horizontal = 16.dp),
                        horizontalArrangement = Arrangement.spacedBy(space = 8.dp),
                    ) {
                        items(
                            items = characteristics.value,
                            key = { it.characteristicId }
                        ) {
                            LevelUpCharacteristic(
                                modifier = Modifier.size(size = MaterialTheme.lwa.dimen.sheet.characteristic),
                                characteristic = it,
                                onClick = { onCharacteristic(it) },
                            )
                        }
                    }
                    Column(
                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                        verticalArrangement = Arrangement.spacedBy(space = 8.dp),
                    ) {
                        skills.value?.commonSkills?.let { skills ->
                            SubSkillSection(
                                modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
                                label = Res.string.character_sheet__skills__common_title,
                                skills = skills,
                                onSkill = onSkill,
                            )
                        }
                        skills.value?.specialSkills?.let { skills ->
                            SubSkillSection(
                                modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
                                label = Res.string.character_sheet__skills__special_title,
                                skills = skills,
                                onSkill = onSkill,
                            )
                        }
                        skills.value?.magicSkills?.let { skills ->
                            SubSkillSection(
                                modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
                                label = Res.string.character_sheet__skills__magic_title,
                                skills = skills,
                                onSkill = onSkill,
                            )
                        }
                    }
                }
            }
        },
    )
}

@Composable
private fun LevelUpLayout(
    modifier: Modifier,
    panelShape: Shape = MaterialTheme.lwa.shapes.panel,
    panelColor: Color = MaterialTheme.lwa.colorScheme.elevated.base1dp,
    topBar: @Composable () -> Unit,
    background: @Composable BoxScope.() -> Unit,
    panel: @Composable BoxScope.() -> Unit,
) {
    Scaffold(
        modifier = modifier,
        topBar = topBar,
        content = { paddingValues ->
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
            ) {
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .offset(x = 128.dp * -2)
                ) {
                    background()
                }
                Box(
                    modifier = Modifier
                        .align(Alignment.CenterEnd)
                        .padding(all = 8.dp)
                        .fillMaxHeight()
                        .width(width = 128.dp * 4)
                        .clip(shape = panelShape)
                        .background(color = panelColor, shape = panelShape)
                ) {
                    panel()
                }
            }
        }
    )
}

@Composable
private fun SubSkillSection(
    modifier: Modifier = Modifier,
    paddingValues: PaddingValues = PaddingValues(bottom = 8.dp, top = 4.dp),
    label: StringResource,
    skills: List<LevelUpSkillUio>,
    onSkill: (LevelUpSkillUio) -> Unit,
) {
    DecoratedBox(
        modifier = modifier,
    ) {
        Column {
            Text(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(paddingValues),
                style = MaterialTheme.typography.caption,
                textAlign = TextAlign.Center,
                text = stringResource(label),
            )
            skills.forEach { skill ->
                LevelUpSkill(
                    modifier = Modifier.height(height = 32.dp),
                    skill = skill,
                    onSkill = onSkill,
                )
            }
        }
    }
}

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

            else -> false
        }
    }
}

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