package cl.homelogic.platform.designsystem.foundations

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

enum class FeedbackType {
    Confirm,
    ContextClick,
    GestureEnd,
    GestureThresholdActivate,
    LongPress,
    Reject,
    SegmentFrequentTick,
    SegmentTick,
    TextHandleMove,
    ToggleOff,
    ToggleOn,
    VirtualKey,
}

class HapticManager(
    private val hapticFeedback: HapticFeedback,
) {
    private val _hapticEnabled = MutableStateFlow(true)
    val status: StateFlow<Boolean> = _hapticEnabled

    fun enable() {
        _hapticEnabled.value = true
    }

    fun disable() {
        _hapticEnabled.value = false
    }

    fun performFeedback(
        type: FeedbackType,
    ) {
        if (!_hapticEnabled.value) return

        with(hapticFeedback) {
            when (type) {
                FeedbackType.Confirm -> performHapticFeedback(HapticFeedbackType.Confirm)
                FeedbackType.ContextClick -> performHapticFeedback(HapticFeedbackType.ContextClick)
                FeedbackType.GestureEnd -> performHapticFeedback(HapticFeedbackType.GestureEnd)
                FeedbackType.GestureThresholdActivate -> performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)
                FeedbackType.LongPress -> performHapticFeedback(HapticFeedbackType.LongPress)
                FeedbackType.Reject -> performHapticFeedback(HapticFeedbackType.Reject)
                FeedbackType.SegmentFrequentTick -> performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
                FeedbackType.SegmentTick -> performHapticFeedback(HapticFeedbackType.SegmentTick)
                FeedbackType.TextHandleMove -> performHapticFeedback(HapticFeedbackType.TextHandleMove)
                FeedbackType.ToggleOff -> performHapticFeedback(HapticFeedbackType.ToggleOff)
                FeedbackType.ToggleOn -> performHapticFeedback(HapticFeedbackType.ToggleOn)
                FeedbackType.VirtualKey -> performHapticFeedback(HapticFeedbackType.VirtualKey)
            }
        }
    }
}

val LocalHapticManager = staticCompositionLocalOf<HapticManager> {
    error("HapticManager not provided")
}

@Composable
fun HapticSystem(
    hapticFeedback: HapticFeedback,
    content: @Composable () -> Unit,
) {
    val hapticManager = HapticManager(hapticFeedback)
    CompositionLocalProvider(LocalHapticManager provides hapticManager) {
        content()
    }
}
