package com.pixelized.desktop.lwa.ui.composable.error

import androidx.compose.material.SnackbarDuration
import androidx.compose.material.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import com.pixelized.desktop.lwa.LocalErrorSnackHost
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.error__default__action
import org.jetbrains.compose.resources.getString

@Stable
class ErrorSnackUio(
    val message: String,
    val action: String,
    val duration: SnackbarDuration,
) {
    companion object {
        suspend fun from(exception: Exception) = ErrorSnackUio(
            message = exception.localizedMessage,
            action = getString(Res.string.error__default__action),
            duration = SnackbarDuration.Long,
        )
    }
}

@Composable
fun ErrorSnackHandler(
    snack: SnackbarHostState = LocalErrorSnackHost.current,
    error: SharedFlow<ErrorSnackUio>,
) {
    LaunchedEffect(Unit) {
        error.collectLatest {
            snack.showSnackbar(
                message = it.message,
                actionLabel = it.action,
                duration = it.duration,
            )
        }
    }
}