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

import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.material.Checkbox
import androidx.compose.material.CheckboxColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import com.pixelized.desktop.lwa.ui.theme.color.component.LwaCheckboxColors
import com.pixelized.desktop.lwa.utils.extention.isElementVisible
import kotlinx.coroutines.flow.StateFlow

@Stable
data class LwaCheckBoxUio(
    val enable: Boolean = true,
    val checked: StateFlow<Boolean>,
    val onCheckedChange: (Boolean) -> Unit,
)

@Composable
fun LwaCheckBox(
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    colors: CheckboxColors = LwaCheckboxColors(),
    field: LwaCheckBoxUio,
) {
    val focus = LocalFocusManager.current

    val isFocused = interactionSource.collectIsFocusedAsState()
    val checked = field.checked.collectAsState()

    Checkbox(
        modifier = Modifier
            .isElementVisible { visible ->
                if (visible.not() && isFocused.value) {
                    focus.clearFocus()
                }
            }
            .then(other = modifier),
        interactionSource = interactionSource,
        enabled = enabled,
        checked = checked.value,
        colors = colors,
        onCheckedChange = field.onCheckedChange,
    )
}