package cl.homelogic.platform.designsystem.components.atoms

import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import cl.homelogic.platform.designsystem.foundations.FeedbackType
import cl.homelogic.platform.designsystem.foundations.LocalHapticManager
import cl.homelogic.platform.designsystem.foundations.Padding
import cl.homelogic.platform.designsystem.foundations.Shapes
import cl.homelogic.platform.designsystem.foundations.Sizes
import kotlin.math.abs
import kotlin.math.roundToInt

@Composable
fun SegmentedControl(
    modifier: Modifier = Modifier,
    items: List<String>,
    initialSelectedIndex: Int,
    onSelectedIndexChange: (Int) -> Unit,
) {
    var selectedIndex by remember { mutableIntStateOf(initialSelectedIndex) }

    val density = LocalDensity.current
    val haptic = LocalHapticManager.current
    var componentWidth by remember { mutableStateOf(0) }
    val itemWidth = remember(componentWidth) { componentWidth.toFloat() / items.size }
    val pillOffset by animateFloatAsState(
        targetValue = itemWidth * selectedIndex,
        animationSpec = spring(
            dampingRatio = 0.83f,
            stiffness = Spring.StiffnessMediumLow,
        ),
        label = "SegmentedControl-pillOffset",
    )

    Box(
        modifier = modifier
            .height(Sizes.Containers.Small)
            .clip(Shapes.RoundCorner.regular)
            .background(MaterialTheme.colorScheme.surfaceVariant)
            .padding(Padding.tiny)
            .onSizeChanged { size ->
                if (componentWidth != size.width) {
                    componentWidth = size.width
                }
            },
    ) {
        // Animated Pill
        Box(
            modifier = Modifier
                .offset { IntOffset(pillOffset.roundToInt(), 0) }
                .width(with(density) { itemWidth.toDp() })
                .fillMaxHeight()
                .shadow(Sizes.Shadows.Regular, shape = Shapes.RoundCorner.small)
                .clip(Shapes.RoundCorner.small)
                .background(MaterialTheme.colorScheme.primaryContainer),
        )

        SegmentedControlItems(items, selectedIndex) { newIndex ->
            if (newIndex != selectedIndex) {
                // Do a stronger vibration if the pill moves more than
                val difference = abs(newIndex - selectedIndex)
                if (difference < 3) {
                    haptic.performFeedback(FeedbackType.SegmentTick)
                } else {
                    haptic.performFeedback(FeedbackType.LongPress)
                }
            }
            selectedIndex = newIndex
            onSelectedIndexChange(newIndex)
        }
    }
}

@Composable
private fun SegmentedControlItems(
    items: List<String>,
    selectedIndex: Int,
    onSelectedIndexChange: (Int) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly,
    ) {
        items.forEachIndexed { index, item ->
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = null,
                    ) {
                        onSelectedIndexChange(index)
                    }.padding(horizontal = Padding.small),
                contentAlignment = Alignment.Center,
            ) {
                Text(
                    text = item,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = if (selectedIndex == index) {
                        MaterialTheme.colorScheme.onSurface
                    } else {
                        MaterialTheme.colorScheme.onSurfaceVariant
                    },
                    style = if (selectedIndex == index) {
                        typography.bodyLarge
                    } else {
                        typography.bodyMedium
                    },
                )
            }
        }
    }
}
