package com.optix.android.ui.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.optix.android.domain.model.ParamType
import com.optix.android.domain.model.ToolMetadata
import com.optix.android.ui.theme.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ToolConfigForm(
    tool: ToolMetadata,
    params: Map<String, String>,
    onParamChange: (String, String) -> Unit,
    onRun: () -> Unit,
    onCancel: () -> Unit,
    isRunning: Boolean,
    modifier: Modifier = Modifier,
    highlightedParams: Set<String> = emptySet(),
) {
    var showTip by remember { mutableStateOf(false) }
    val tip = ToolTips.get(tool.name)

    Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {

        // Beginner tip card
        if (tip != null) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .border(1.dp, T.accentGlow.copy(alpha = 0.3f), RoundedCornerShape(8.dp))
                    .background(T.accentGlow.copy(alpha = 0.06f), RoundedCornerShape(8.dp))
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { showTip = !showTip }
                        .padding(horizontal = 12.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Text(
                        "ℹ️  What does this tool do?",
                        color = T.accentGlow,
                        fontSize = 13.sp,
                    )
                    Icon(
                        if (showTip) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                        contentDescription = null,
                        tint = T.accentGlow,
                    )
                }
                AnimatedVisibility(visible = showTip) {
                    Column(modifier = Modifier.padding(horizontal = 12.dp).padding(bottom = 10.dp)) {
                        Text(tip.whatItDoes, color = T.onSurface, fontSize = 13.sp, lineHeight = 18.sp)
                        Spacer(Modifier.height(8.dp))
                        Text("📊 What to look for:", color = T.accentGlow, fontSize = 12.sp)
                        Text(tip.whatToLookFor, color = T.onSurfaceMid, fontSize = 12.sp, lineHeight = 17.sp)
                        if (tip.exampleValue != null) {
                            Spacer(Modifier.height(6.dp))
                            Text("💡 Example: ${tip.exampleValue}", color = T.warning, fontSize = 11.sp, fontStyle = FontStyle.Italic)
                        }
                    }
                }
            }
        }

        // Parameters
        tool.parameters.forEach { param ->
            when (param.type) {
                ParamType.BOOLEAN -> {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Text(param.description, color = T.onSurface, style = MaterialTheme.typography.bodyMedium)
                        Switch(
                            checked = params[param.name]?.toBooleanStrictOrNull() ?: false,
                            onCheckedChange = { onParamChange(param.name, it.toString()) },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = T.accent,
                                checkedTrackColor = T.accent.copy(alpha = 0.3f),
                                uncheckedThumbColor = T.onSurfaceMid,
                                uncheckedTrackColor = T.border
                            ),
                        )
                    }
                }
                ParamType.ENUM -> {
                    var expanded by remember { mutableStateOf(false) }
                    val current = params[param.name] ?: param.defaultValue ?: param.enumValues.firstOrNull() ?: ""
                    ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
                        OutlinedTextField(
                            value = current,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text(param.description, color = T.onSurfaceMid) },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded) },
                            modifier = Modifier.fillMaxWidth().menuAnchor(),
                            colors = neonTextFieldColors(),
                        )
                        ExposedDropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.background(T.surface)
                        ) {
                            param.enumValues.forEach { option ->
                                DropdownMenuItem(
                                    text = { Text(option, color = T.onSurface) },
                                    onClick = { onParamChange(param.name, option); expanded = false },
                                )
                            }
                        }
                    }
                }
                ParamType.INT, ParamType.STRING -> {
                    val isHighlighted = param.name in highlightedParams
                    val keyboardType = if (param.type == ParamType.INT) KeyboardType.Number else KeyboardType.Text
                    OutlinedTextField(
                        value = params[param.name] ?: param.defaultValue ?: "",
                        onValueChange = { onParamChange(param.name, it) },
                        label = { Text(param.description, color = if (isHighlighted) T.success else T.onSurfaceMid) },
                        keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
                        modifier = Modifier.fillMaxWidth(),
                        colors = if (isHighlighted) neonTextFieldColors(accent = T.success) else neonTextFieldColors(),
                        singleLine = true,
                        trailingIcon = if (isHighlighted) ({
                            Icon(Icons.Default.CheckCircle, contentDescription = null, tint = T.success, modifier = Modifier.size(16.dp))
                        }) else null,
                    )
                }
            }
        }

        Spacer(Modifier.height(4.dp))

        NeonButton(
            label = if (isRunning) "STOP TOOL" else "RUN TOOL",
            onClick = if (isRunning) onCancel else onRun,
            color = if (isRunning) T.warning else T.accent,
            modifier = Modifier.fillMaxWidth()
        )
    }
}
