package compose.widgets

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.pointer.PointerIcon
import androidx.compose.ui.input.pointer.pointerHoverIcon
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import compose.input.KeyShortcut
import compose.input.onKeyShortcut


/**
 * A Text-like widget which becomes editable when double-clicked.
 */
@Composable
@OptIn(ExperimentalFoundationApi::class)
fun EditableText(
    text: String,
    modifier: Modifier = Modifier,
){
    var isEditing by remember { mutableStateOf(false) }
    var textValue by remember { mutableStateOf(TextFieldValue(text)) }
    val textFieldFocusRequester = remember { FocusRequester() }
    val interactionSource = remember { MutableInteractionSource() }

    BasicTextField(
        value = textValue,
        onValueChange = { textValue = it },
        singleLine = true,
        enabled = isEditing,
        interactionSource = interactionSource,
        modifier = modifier
            .pointerHoverIcon(
                if (isEditing) PointerIcon.Text else PointerIcon.Default, overrideDescendants = true
            )
            .onFocusChanged {
                if (!it.hasFocus)
                    isEditing = false
            }
            .onKeyShortcut(KeyShortcut.anyEnter(), onPreview = true) {
                isEditing = false
                textValue = textValue.copy(
                    selection = TextRange.Zero
                )
            }
            .combinedClickable(
                onDoubleClick = {
                    isEditing = true
                    textValue = textValue.copy(
                        selection = TextRange(0, textValue.text.length)
                    )
                },
                indication = null,
                interactionSource = interactionSource,
                onClick = {}
            )
            .focusRequester(textFieldFocusRequester)
            .fillMaxWidth()
    )
    if (isEditing){
        LaunchedEffect(Unit){
            textFieldFocusRequester.requestFocus()
        }
    }
}
