package ch.dissem.yaep.ui.common.layout

import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.graphics.Color
import ch.dissem.yaep.ui.common.focus.FocusFollowingFocusable

@Composable
fun FocusBox(focusable: FocusFollowingFocusable, requestFocus: Boolean = false) {
    val hasFocus by focusable.hasFocus.collectAsState(false)
    Box(
        modifier = Modifier
            .focusRequester(focusable.focusRequester)
            .onFocusEvent { state ->
                focusable.setFocus(state)
            }
            .onFocusChanged {}
            .focusable()
            .clip(MaterialTheme.shapes.small)
            .background(
                if (hasFocus) {
                    MaterialTheme.colorScheme.surfaceContainerHigh
                } else {
                    Color.Transparent
                }
            ),
    )
    if (requestFocus) {
        LaunchedEffect(Unit) {
            focusable.focusRequester.requestFocus()
        }
    }
}