package cl.homelogic.platform.designsystem.extensions

import androidx.compose.foundation.Indication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.semantics.disabled
import androidx.compose.ui.semantics.semantics

fun Modifier.disable(): Modifier =
    this
        .alpha(0.3f)
        .clickable(enabled = false) {}
        .focusable(false)
        .semantics {
            disabled()
        }.pointerInput(Unit) {
            awaitPointerEventScope {
                while (true) {
                    val event = awaitPointerEvent(PointerEventPass.Initial)
                    event.changes.forEach { pointerInputChange: PointerInputChange ->
                        pointerInputChange.consume()
                    }
                }
            }
        }

fun Modifier.clickable(status: Boolean): Modifier =
    if (status) {
        this
    } else {
        this.disable()
    }

fun Modifier.intangible(): Modifier =
    this
        .alpha(0.3f)

fun Modifier.conditionalClickable(
    onClick: (() -> Unit)?,
    interactionSource: MutableInteractionSource,
    indication: Indication?,
): Modifier =
    if (onClick != null) {
        this.clickable(
            interactionSource = interactionSource,
            indication = indication,
            onClick = onClick,
        )
    } else {
        this
    }
