package com.pixelized.headache.ui.common.error

import android.content.Context
import androidx.annotation.StringRes
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.ui.platform.LocalContext
import com.pixelized.headache.ui.page.LocalSnack
import kotlinx.coroutines.flow.Flow

@Stable
sealed interface ErrorToast

@Stable
data class StringErrorMessage(
    val message: String,
) : ErrorToast

@Stable
data class ResourceErrorMessage(
    @StringRes val message: Int,
) : ErrorToast

@Composable
fun HandleErrorMessage(
    context: Context = LocalContext.current,
    snack: SnackbarHostState = LocalSnack.current,
    errors: Flow<ErrorToast>,
) {
    LaunchedEffect(Unit) {
        errors.collect { message ->
            snack.showSnackbar(
                message = when (message) {
                    is StringErrorMessage -> message.message
                    is ResourceErrorMessage -> context.getString(message.message)
                },
            )
        }
    }
}
