package com.placeholder.sherpai2.ui.discover

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.*
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.text.font.FontWeight
import androidx.compose.ui.unit.dp

/**
 * DiscoverySettingsCard - Quality control sliders
 *
 * Allows tuning without dropping quality:
 * - Face size threshold (bigger = more strict)
 * - Quality score threshold (higher = better faces)
 * - Clustering strictness (tighter = more clusters)
 */
@Composable
fun DiscoverySettingsCard(
    settings: DiscoverySettings,
    onSettingsChange: (DiscoverySettings) -> Unit,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }

    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        )
    ) {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            // Header - Always visible
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Default.Tune,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Column {
                        Text(
                            text = "Quality Settings",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = if (expanded) "Hide settings" else "Tap to adjust",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                IconButton(onClick = { expanded = !expanded }) {
                    Icon(
                        imageVector = if (expanded) Icons.Default.ExpandLess
                        else Icons.Default.ExpandMore,
                        contentDescription = if (expanded) "Collapse" else "Expand"
                    )
                }
            }

            // Settings - Expandable
            AnimatedVisibility(
                visible = expanded,
                enter = expandVertically(),
                exit = shrinkVertically()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .padding(bottom = 16.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp)
                ) {
                    HorizontalDivider()

                    // Face Size Slider
                    QualitySlider(
                        title = "Minimum Face Size",
                        description = "Smaller = more faces, larger = higher quality",
                        currentValue = "${(settings.minFaceSize * 100).toInt()}%",
                        value = settings.minFaceSize,
                        onValueChange = { onSettingsChange(settings.copy(minFaceSize = it)) },
                        valueRange = 0.02f..0.08f,
                        icon = Icons.Default.ZoomIn
                    )

                    // Quality Score Slider
                    QualitySlider(
                        title = "Quality Threshold",
                        description = "Lower = more faces, higher = better quality",
                        currentValue = "${(settings.minQuality * 100).toInt()}%",
                        value = settings.minQuality,
                        onValueChange = { onSettingsChange(settings.copy(minQuality = it)) },
                        valueRange = 0.4f..0.8f,
                        icon = Icons.Default.HighQuality
                    )

                    // Clustering Strictness
                    QualitySlider(
                        title = "Clustering Strictness",
                        description = when {
                            settings.epsilon < 0.20f -> "Very strict (more clusters)"
                            settings.epsilon > 0.25f -> "Loose (fewer clusters)"
                            else -> "Balanced"
                        },
                        currentValue = when {
                            settings.epsilon < 0.20f -> "Strict"
                            settings.epsilon > 0.25f -> "Loose"
                            else -> "Normal"
                        },
                        value = settings.epsilon,
                        onValueChange = { onSettingsChange(settings.copy(epsilon = it)) },
                        valueRange = 0.16f..0.28f,
                        icon = Icons.Default.Category
                    )

                    HorizontalDivider()

                    // Info Card
                    InfoCard(
                        text = "These settings control face quality, not photo type. " +
                                "Group photos are included - we extract the best face from each."
                    )

                    // Preset Buttons
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        OutlinedButton(
                            onClick = { onSettingsChange(DiscoverySettings.STRICT) },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("High Quality", style = MaterialTheme.typography.bodySmall)
                        }

                        Button(
                            onClick = { onSettingsChange(DiscoverySettings.DEFAULT) },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("Balanced", style = MaterialTheme.typography.bodySmall)
                        }

                        OutlinedButton(
                            onClick = { onSettingsChange(DiscoverySettings.LOOSE) },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("More Faces", style = MaterialTheme.typography.bodySmall)
                        }
                    }
                }
            }
        }
    }
}

/**
 * Individual quality slider component
 */
@Composable
private fun QualitySlider(
    title: String,
    description: String,
    currentValue: String,
    value: Float,
    onValueChange: (Float) -> Unit,
    valueRange: ClosedFloatingPointRange<Float>,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    Column(
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Header
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.weight(1f)
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(20.dp)
                )
                Text(
                    text = title,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium
                )
            }

            Surface(
                shape = MaterialTheme.shapes.small,
                color = MaterialTheme.colorScheme.primaryContainer
            ) {
                Text(
                    text = currentValue,
                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
                    style = MaterialTheme.typography.labelLarge,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.Bold
                )
            }
        }

        // Description
        Text(
            text = description,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        // Slider
        Slider(
            value = value,
            onValueChange = onValueChange,
            valueRange = valueRange
        )
    }
}

/**
 * Info card component
 */
@Composable
private fun InfoCard(text: String) {
    Card(
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f)
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Info,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSecondaryContainer,
                modifier = Modifier.size(18.dp)
            )
            Text(
                text = text,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
        }
    }
}

/**
 * Discovery settings data class
 */
data class DiscoverySettings(
    val minFaceSize: Float = 0.03f,      // 3% of image (balanced)
    val minQuality: Float = 0.6f,         // 60% quality (good)
    val epsilon: Float = 0.22f            // DBSCAN threshold (balanced)
) {
    companion object {
        // Balanced - Default recommended settings
        val DEFAULT = DiscoverySettings(
            minFaceSize = 0.03f,
            minQuality = 0.6f,
            epsilon = 0.22f
        )

        // Strict - High quality, fewer faces
        val STRICT = DiscoverySettings(
            minFaceSize = 0.05f,   // 5% of image
            minQuality = 0.7f,      // 70% quality
            epsilon = 0.18f         // Tight clustering
        )

        // Loose - More faces, lower quality threshold
        val LOOSE = DiscoverySettings(
            minFaceSize = 0.02f,   // 2% of image
            minQuality = 0.5f,      // 50% quality
            epsilon = 0.26f         // Loose clustering
        )
    }
}