package com.pixelized.biblib.utils.extention

import android.annotation.SuppressLint
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.AutofillNode
import androidx.compose.ui.autofill.AutofillType
import androidx.compose.ui.composed
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalAutofill
import androidx.compose.ui.platform.LocalAutofillTree
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.placeholder
import com.google.accompanist.placeholder.shimmer

@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.autofill(
    autofillTypes: List<AutofillType>,
    onFill: ((String) -> Unit),
) = composed {
    val autofill = LocalAutofill.current
    val autofillNode = AutofillNode(
        onFill = onFill,
        autofillTypes = autofillTypes
    )
    LocalAutofillTree.current += autofillNode

    return@composed this
        .onGloballyPositioned {
            autofillNode.boundingBox = it.boundsInWindow()
        }
        .onFocusChanged { focusState ->
            when (focusState.isFocused) {
                true -> autofill?.requestAutofillForNode(autofillNode)
                else -> autofill?.cancelAutofillForNode(autofillNode)
            }
        }
}

@SuppressLint("ComposableModifierFactory")
@Composable
fun Modifier.placeholder(
    color: Color = MaterialTheme.bibLib.colors.placeHolder.color,
    shimmer: Color? = MaterialTheme.bibLib.colors.placeHolder.shimmer,
    shape: Shape = CircleShape,
    isShimmering: () -> Boolean = { true },
    visible: () -> Boolean,
) = this.placeholder(
    visible = visible(),
    color = color,
    shape = shape,
    highlight = shimmer
        ?.takeIf { isShimmering() }
        ?.let { PlaceholderHighlight.shimmer(highlightColor = it) },
)