package com.pixelized.biblib.ui.composable.scaffold

import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable

@Composable
fun HandleBottomSheetData(
    bottomSheetData: Any?,
    shouldShow: suspend () -> Unit,
    shouldDismiss: suspend () -> Unit,
) {
    val currentShouldShow by rememberUpdatedState(
        newValue = shouldShow
    )
    val currentShouldDismiss by rememberUpdatedState(
        newValue = shouldDismiss
    )
    LaunchedEffect(bottomSheetData) {
        when (bottomSheetData) {
            null -> currentShouldDismiss()
            else -> currentShouldShow()
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HandleBottomSheetDismiss(
    bottomSheetState: ModalBottomSheetState,
    onDismiss: () -> Unit,
) {
    val currentOnDismiss by rememberUpdatedState(
        newValue = onDismiss,
    )
    // Showing a bottom sheet produce a :
    // - currentValue == Hidden targetValue == Hidden
    // before a :
    // - currentValue == Hidden targetValue == Expanded
    // We need to keep track of this behavior to avoid closing the bottom sheet immediately.
    var skipLaunchEffect by rememberSaveable {
        mutableStateOf(true)
    }
    LaunchedEffect(bottomSheetState.currentValue) {
        if (skipLaunchEffect.not()) {
            if (bottomSheetState.currentValue == ModalBottomSheetValue.Hidden && bottomSheetState.targetValue == ModalBottomSheetValue.Hidden) {
                currentOnDismiss()
                skipLaunchEffect = true
            }
        } else {
            skipLaunchEffect = false
        }
    }
}