package eu.gaudian.translator.view.hints

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.view.composable.AppIcons

/**
 * A CompositionLocal to provide the "show hints" setting down the component tree.
 * This avoids having to pass the setting as a parameter to every composable.
 * The default value is `false`.
 */
val LocalShowHints = compositionLocalOf { false }

/**
 * A wrapper composable that adds an optional hint button next to its content.
 * The button is only visible if the 'LocalShowHints' CompositionLocal is true.
 * When clicked, it displays the provided hint content in a ModalBottomSheet.
 *
 * @param hintContent The composable content to display inside the ModalBottomSheet.
 * @param modifier The modifier to be applied to the layout.
 * @param content The main composable content that this hint is for.
 */
@Composable
fun WithHint(
    modifier: Modifier = Modifier,
    hintContent: Hint? = null,
    content: @Composable () -> Unit
) {
    val showHints = LocalShowHints.current

    val sheetState = rememberModalBottomSheetState()
    var showBottomSheet by remember { mutableStateOf(false) }

    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically
    ) {
        content()

        if (showHints) {
            IconButton(
                onClick = { showBottomSheet = true },
                modifier = Modifier.padding(start = 4.dp)
            ) {
                Icon(
                    imageVector = AppIcons.Help,
                    contentDescription = stringResource(R.string.show_hint),
                    tint = MaterialTheme.colorScheme.secondary
                )
            }
        }
    }

    if (showBottomSheet) {
        hintContent?.let {
            HintBottomSheet(
                onDismissRequest = {
                    @Suppress("AssignedValueIsNeverRead")
                    showBottomSheet = false
                },
                sheetState = sheetState,
                content = it,
            )
        }
    }
}

