package solutions.tretter.mindmachine.session

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp

@Composable
fun FlashSequenceEditor(
    sequence: List<FlashSequenceRow>,
    onSequenceChanged: (List<FlashSequenceRow>) -> Unit,
    modifier: Modifier = Modifier,
) {
    val rows = sequence.ifEmpty { defaultFlashSequence() }
    val splitColWidth = 56.dp
    val deleteColWidth = 40.dp

    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(12.dp))
            .padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Text("Color sequence", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface)
        Text(
            "Each row is one visible color state. Split screen uses separate left/right colors. Non-split rows fill the whole screen with one color.",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.72f),
        )

        // Table header row.
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Box(modifier = Modifier.width(splitColWidth), contentAlignment = Alignment.CenterStart) {
                Text("Split", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurface)
            }
            Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
                Text("Left", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurface)
            }
            Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
                Text("Right", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurface)
            }
            Box(modifier = Modifier.width(deleteColWidth))
        }

        rows.forEachIndexed { index, row ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                Box(modifier = Modifier.width(splitColWidth), contentAlignment = Alignment.CenterStart) {
                    Checkbox(
                        checked = row.splitScreen,
                        onCheckedChange = { checked ->
                            onSequenceChanged(rows.toMutableList().also { it[index] = row.copy(splitScreen = checked) })
                        }
                    )
                }

                ColorCycleButton(
                    color = row.leftColor,
                    onClick = {
                        onSequenceChanged(rows.toMutableList().also {
                            it[index] = row.copy(leftColor = row.leftColor.next())
                        })
                    },
                    modifier = Modifier.weight(1f),
                )

                if (row.splitScreen) {
                    ColorCycleButton(
                        color = row.rightColor,
                        onClick = {
                            onSequenceChanged(rows.toMutableList().also {
                                it[index] = row.copy(rightColor = row.rightColor.next())
                            })
                        },
                        modifier = Modifier.weight(1f),
                    )
                } else {
                    Box(modifier = Modifier.weight(1f))
                }

                IconButton(
                    onClick = {
                        onSequenceChanged(rows.filterIndexed { i, _ -> i != index }.ifEmpty { defaultFlashSequence() })
                    },
                    modifier = Modifier.width(deleteColWidth),
                ) {
                    Icon(Icons.Default.Delete, contentDescription = "Remove row", tint = MaterialTheme.colorScheme.onSurface)
                }
            }
        }

        OutlinedButton(
            onClick = { onSequenceChanged(rows + FlashSequenceRow()) },
            modifier = Modifier.fillMaxWidth(),
        ) {
            Icon(Icons.Default.Add, contentDescription = null)
            Text(" Add color row")
        }
    }
}

@Composable
private fun ColorCycleButton(
    color: FlashPaletteColor,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    OutlinedButton(
        onClick = onClick,
        modifier = modifier.heightIn(min = 40.dp),
        contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
    ) {
        Box(
            modifier = Modifier
                .padding(end = 8.dp)
                .background(color.previewColor(), RoundedCornerShape(6.dp))
                .padding(horizontal = 10.dp, vertical = 8.dp)
        )
        Text(
            text = color.displayName,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

private val FlashPaletteColor.displayName: String
    get() = name.lowercase().replaceFirstChar { it.uppercase() }

private fun FlashPaletteColor.next(): FlashPaletteColor {
    val values = FlashPaletteColor.entries
    return values[(ordinal + 1) % values.size]
}

private fun FlashPaletteColor.previewColor(): Color = when (this) {
    FlashPaletteColor.BLACK -> Color.Black
    FlashPaletteColor.WHITE -> Color.White
    FlashPaletteColor.RED -> Color(0xFFD32F2F)
    FlashPaletteColor.GREEN -> Color(0xFF2E7D32)
    FlashPaletteColor.YELLOW -> Color(0xFFF9A825)
    FlashPaletteColor.BLUE -> Color(0xFF1565C0)
}
