package com.pixelized.desktop.lwa.ui.overlay.roll

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
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 com.pixelized.desktop.lwa.LocalBlurController
import com.pixelized.desktop.lwa.ui.composable.key.KeyHandler
import kotlinx.coroutines.launch
import org.koin.compose.viewmodel.koinViewModel


@Composable
fun RollOverlay(
    viewModel: RollViewModel = koinViewModel(),
    modifier: Modifier = Modifier,
    hostState: RollHostState,
) {
    val blur = LocalBlurController.current
    val scope = rememberCoroutineScope()

    hostState.rollAction.value.let {
        LaunchedEffect(it) {
            if (it != null) {
                blur.show()
                viewModel.prepareRoll(roll = it.roll)
            } else {
                viewModel.cleanRoll()
                blur.hide()
            }
        }
    }

    AnimatedContent(
        modifier = modifier,
        targetState = hostState.rollAction.value,
        transitionSpec = {
            val enter = fadeIn() + slideInVertically { 64 }
            val exit = fadeOut() + slideOutVertically { 64 }
            enter togetherWith exit
        },
    ) { roll ->
        when (roll) {
            null -> Box(
                modifier = Modifier.fillMaxSize()
            )

            else -> Box(
                modifier = Modifier.fillMaxSize()
            ) {
                RollOverlayKeyHandler(
                    onDismissRequest = {
                        roll.action(result = viewModel.lastRollResult)
                    }
                )

                RollPage(
                    viewModel = viewModel,
                    onDismissRequest = {
                        roll.action(result = viewModel.lastRollResult)
                    },
                    onRoll = {
                        scope.launch {
                            viewModel.roll()
                        }
                    }
                )
            }
        }
    }
}

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

            else -> false
        }
    }
}