package app.voltplan.cable.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
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 androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.voltplan.cable.ui.sfSymbol
import app.voltplan.cable.ui.theme.componentColor
import app.voltplan.cable.ui.theme.curatedColorNames

/**
 * Bottom-sheet editor for a component's name, icon and color. Mirrors `ItemEditorView`.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppearanceEditorSheet(
    title: String,
    nameLabel: String,
    previewSubtitle: String,
    icons: List<String>,
    initialName: String,
    initialIcon: String,
    initialColor: String,
    onSave: (name: String, iconName: String, colorName: String) -> Unit,
    onDismiss: () -> Unit,
    extra: (@Composable () -> Unit)? = null,
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    var name by remember { mutableStateOf(initialName) }
    var icon by remember { mutableStateOf(initialIcon) }
    var color by remember { mutableStateOf(initialColor) }
    val selectedColor = componentColor(color)

    ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
        Column(
            Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp)
                .padding(bottom = 24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold)
                androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
                TextButton(onClick = { onSave(name, icon, color); onDismiss() }) {
                    Text("Save", fontWeight = FontWeight.SemiBold)
                }
            }

            // Preview row
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                LoadIcon(
                    remoteIconURLString = null,
                    fallbackSymbol = icon,
                    fallbackColor = selectedColor,
                    size = 60.dp,
                )
                Column {
                    Text(
                        name.ifBlank { nameLabel },
                        style = MaterialTheme.typography.titleMedium,
                    )
                    Text(
                        previewSubtitle,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }

            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text(nameLabel) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth(),
            )

            extra?.invoke()

            Text("Icon", style = MaterialTheme.typography.titleSmall)
            LazyVerticalGrid(
                columns = GridCells.Fixed(5),
                modifier = Modifier.fillMaxWidth().heightForRows(icons.size, 5),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                userScrollEnabled = false,
            ) {
                items(icons) { symbol ->
                    val selected = symbol == icon
                    Box(
                        Modifier
                            .aspectRatio(1f)
                            .clip(RoundedCornerShape(12.dp))
                            .background(if (selected) selectedColor else MaterialTheme.colorScheme.surfaceVariant)
                            .clickable { icon = symbol },
                        contentAlignment = Alignment.Center,
                    ) {
                        Icon(
                            sfSymbol(symbol),
                            contentDescription = symbol,
                            tint = if (selected) Color.White else MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(24.dp),
                        )
                    }
                }
            }

            Text("Color", style = MaterialTheme.typography.titleSmall)
            LazyVerticalGrid(
                columns = GridCells.Fixed(6),
                modifier = Modifier.fillMaxWidth().heightForRows(curatedColorNames.size, 6),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                userScrollEnabled = false,
            ) {
                items(curatedColorNames) { colorName ->
                    val c = componentColor(colorName)
                    Box(
                        Modifier
                            .aspectRatio(1f)
                            .clip(CircleShape)
                            .background(c)
                            .border(2.dp, if (colorName == color) Color.White else Color.Transparent, CircleShape)
                            .clickable { color = colorName },
                        contentAlignment = Alignment.Center,
                    ) {
                        if (colorName == color) {
                            Icon(Icons.Filled.Check, contentDescription = null, tint = Color.White, modifier = Modifier.size(20.dp))
                        }
                    }
                }
            }
        }
    }
}

private fun Modifier.heightForRows(itemCount: Int, columns: Int): Modifier {
    val rows = (itemCount + columns - 1) / columns
    // ~56dp per cell including spacing; gives a non-scrolling grid inside the sheet.
    return this.height((rows * 56).dp)
}
