package cl.homelogic.platform.designsystem.components.molecules

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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 cl.homelogic.platform.designsystem.components.atoms.SimpleCard
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.Sizes

data class RadioButtonItem<T>(
    val text: String,
    val data: T,
)

@Composable
fun <T> RadioButtonSelector(
    items: List<RadioButtonItem<T>>,
    initialSelection: RadioButtonItem<T>? = null,
    onItemSelected: (T) -> Unit,
    modifier: Modifier = Modifier,
) {
    var selectedItem by remember { mutableStateOf(initialSelection) }
    val haptic = LocalHapticManager.current

    Column(
        modifier = modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(Sizes.Spacers.Regular),
    ) {
        items.forEach { item ->
            SelectorOption(
                item = item,
                isSelected = item == selectedItem,
                onSelect = {
                    haptic.performFeedback(FeedbackType.SegmentTick)
                    selectedItem = item
                    onItemSelected(item.data)
                },
            )
        }
    }
}

@Composable
private fun <T> SelectorOption(
    item: RadioButtonItem<T>,
    isSelected: Boolean,
    onSelect: () -> Unit,
) {
    SimpleCard(
        onClick = onSelect,
        modifier = Modifier.wrapContentHeight(),
    ) {
        Row(
            modifier = Modifier
                .padding(Padding.small)
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                modifier = Modifier.padding(start = Padding.small),
                text = item.text,
                style = MaterialTheme.typography.bodyMedium,
            )

            RadioButton(
                selected = isSelected,
                onClick = onSelect,
            )
        }
    }
}
