package xyz.cottongin.radio247.ui.screens.stationlist

import androidx.compose.foundation.clickable
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.unit.dp
import org.json.JSONArray

/**
 * Formats a quality key for display: "256-ssl" → "256 kbps (SSL)", "128-nossl" → "128 kbps"
 */
fun formatQualityForDisplay(key: String): String {
    val parts = key.split("-")
    val kbps = parts.getOrNull(0) ?: key
    val ssl = parts.getOrNull(1) == "ssl"
    return if (ssl) "$kbps kbps (SSL)" else "$kbps kbps"
}

@Composable
fun QualityOverrideDialog(
    currentOrder: List<String>,
    availableQualities: List<String>,
    onDismiss: () -> Unit,
    onSave: (String?) -> Unit,
    modifier: Modifier = Modifier
) {
    var selectedOrder by remember(currentOrder, availableQualities) {
        mutableStateOf(
            if (currentOrder.isEmpty()) availableQualities
            else currentOrder.filter { it in availableQualities } + availableQualities.filter { it !in currentOrder }
        )
    }
    var useDefault by remember(currentOrder) {
        mutableStateOf(currentOrder.isEmpty())
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Quality Preference") },
        text = {
            Column(
                modifier = modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState())
            ) {
                Text(
                    text = "Select your preferred quality order (first = highest priority):",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                availableQualities.forEach { quality ->
                    val selectQuality: () -> Unit = {
                        useDefault = false
                        selectedOrder = listOf(quality) + availableQualities.filter { it != quality }
                    }
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable(onClick = selectQuality)
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(
                            selected = !useDefault && selectedOrder.firstOrNull() == quality,
                            onClick = selectQuality
                        )
                        Text(
                            text = formatQualityForDisplay(quality),
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                    }
                }
                TextButton(
                    onClick = { useDefault = true },
                    modifier = Modifier.padding(top = 8.dp)
                ) {
                    Text("Use Default")
                }
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    if (useDefault) {
                        onSave(null)
                    } else {
                        onSave(JSONArray(selectedOrder).toString())
                    }
                    onDismiss()
                }
            ) {
                Text("Save")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}
