package com.placeholder.sherpai2.ui.discover

import androidx.compose.foundation.layout.*
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.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.placeholder.sherpai2.domain.clustering.AnnotatedCluster
import com.placeholder.sherpai2.domain.clustering.ClusterQualityAnalyzer
import com.placeholder.sherpai2.domain.clustering.ClusterQualityResult

/**
 * TemporalNamingDialog - ENHANCED with age input for temporal clustering
 *
 * NEW FEATURES:
 * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 * ✅ Name field: "Emma"
 * ✅ Age field: "2" (optional but recommended)
 * ✅ Year display: "Photos from 2020"
 * ✅ Auto-suggest: If year=2020 and DOB=2018 → Age=2
 *
 * NAMING PATTERNS:
 * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 * Adults:
 * - Name: "John Doe"
 * - Age: (leave empty)
 * - Result: Person "John Doe" with single model
 *
 * Children (with age):
 * - Name: "Emma"
 * - Age: "2"
 * - Year: "2020"
 * - Result: Person "Emma" with submodel "Emma_Age_2"
 *
 * Children (without age):
 * - Name: "Emma"
 * - Age: (empty)
 * - Year: "2020"
 * - Result: Person "Emma" with submodel "Emma_2020"
 */
@Composable
fun TemporalNamingDialog(
    annotatedCluster: AnnotatedCluster,
    onConfirm: (name: String, age: Int?, isChild: Boolean) -> Unit,
    onDismiss: () -> Unit,
    qualityAnalyzer: ClusterQualityAnalyzer
) {
    var name by remember { mutableStateOf(annotatedCluster.suggestedName ?: "") }
    var ageText by remember { mutableStateOf(annotatedCluster.suggestedAge?.toString() ?: "") }
    var isChild by remember { mutableStateOf(annotatedCluster.suggestedAge != null) }

    // Analyze cluster quality
    val qualityResult = remember(annotatedCluster.cluster) {
        qualityAnalyzer.analyzeCluster(annotatedCluster.cluster)
    }

    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // Header
                Text(
                    text = "Name This Person",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold
                )

                // Year badge
                YearBadge(year = annotatedCluster.year)

                HorizontalDivider()

                // Quality warnings
                QualityWarnings(qualityResult)

                // Name field
                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it },
                    label = { Text("Name") },
                    placeholder = { Text("e.g., Emma") },
                    leadingIcon = {
                        Icon(Icons.Default.Person, contentDescription = null)
                    },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )

                // Child checkbox
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Checkbox(
                        checked = isChild,
                        onCheckedChange = { isChild = it }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Column {
                        Text(
                            text = "This is a child",
                            style = MaterialTheme.typography.bodyMedium
                        )
                        Text(
                            text = "Enable age-specific models",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                // Age field (only if child)
                if (isChild) {
                    OutlinedTextField(
                        value = ageText,
                        onValueChange = {
                            // Only allow numbers
                            if (it.isEmpty() || it.all { c -> c.isDigit() }) {
                                ageText = it
                            }
                        },
                        label = { Text("Age in ${annotatedCluster.year}") },
                        placeholder = { Text("e.g., 2") },
                        leadingIcon = {
                            Icon(Icons.Default.DateRange, contentDescription = null)
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        supportingText = {
                            Text("Optional: Helps create age-specific models")
                        }
                    )

                    // Model name preview
                    if (name.isNotBlank()) {
                        Card(
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.primaryContainer
                            )
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Info,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.onPrimaryContainer
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Column {
                                    Text(
                                        text = "Model will be created as:",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onPrimaryContainer
                                    )
                                    Text(
                                        text = buildModelName(name, ageText, annotatedCluster.year),
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.onPrimaryContainer
                                    )
                                }
                            }
                        }
                    }
                }

                // Cluster stats
                ClusterStats(qualityResult)

                HorizontalDivider()

                // Actions
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Cancel")
                    }

                    Button(
                        onClick = {
                            val age = ageText.toIntOrNull()
                            onConfirm(name, age, isChild)
                        },
                        modifier = Modifier.weight(1f),
                        enabled = name.isNotBlank() && qualityResult.canTrain
                    ) {
                        Text("Create")
                    }
                }
            }
        }
    }
}

/**
 * Year badge showing photo year
 */
@Composable
private fun YearBadge(year: String) {
    Surface(
        color = MaterialTheme.colorScheme.secondaryContainer,
        shape = MaterialTheme.shapes.small
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            Icon(
                imageVector = Icons.Default.DateRange,
                contentDescription = null,
                modifier = Modifier.size(16.dp),
                tint = MaterialTheme.colorScheme.onSecondaryContainer
            )
            Text(
                text = "Photos from $year",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
        }
    }
}

/**
 * Quality warnings
 */
@Composable
private fun QualityWarnings(qualityResult: ClusterQualityResult) {
    if (qualityResult.warnings.isNotEmpty()) {
        Card(
            colors = CardDefaults.cardColors(
                containerColor = when (qualityResult.qualityTier) {
                    com.placeholder.sherpai2.domain.clustering.ClusterQualityTier.POOR ->
                        MaterialTheme.colorScheme.errorContainer
                    com.placeholder.sherpai2.domain.clustering.ClusterQualityTier.GOOD ->
                        MaterialTheme.colorScheme.tertiaryContainer
                    else -> MaterialTheme.colorScheme.surfaceVariant
                }
            )
        ) {
            Column(
                modifier = Modifier.padding(12.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                qualityResult.warnings.take(3).forEach { warning ->
                    Row(
                        verticalAlignment = Alignment.Top,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Icon(
                            imageVector = when (qualityResult.qualityTier) {
                                com.placeholder.sherpai2.domain.clustering.ClusterQualityTier.POOR ->
                                    Icons.Default.Warning
                                else -> Icons.Default.Info
                            },
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = when (qualityResult.qualityTier) {
                                com.placeholder.sherpai2.domain.clustering.ClusterQualityTier.POOR ->
                                    MaterialTheme.colorScheme.onErrorContainer
                                else -> MaterialTheme.colorScheme.onSurfaceVariant
                            }
                        )
                        Text(
                            text = warning,
                            style = MaterialTheme.typography.bodySmall,
                            color = when (qualityResult.qualityTier) {
                                com.placeholder.sherpai2.domain.clustering.ClusterQualityTier.POOR ->
                                    MaterialTheme.colorScheme.onErrorContainer
                                else -> MaterialTheme.colorScheme.onSurfaceVariant
                            }
                        )
                    }
                }
            }
        }
    }
}

/**
 * Cluster statistics
 */
@Composable
private fun ClusterStats(qualityResult: ClusterQualityResult) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly
    ) {
        StatItem(
            label = "Photos",
            value = qualityResult.soloPhotoCount.toString()
        )
        StatItem(
            label = "Clean Faces",
            value = qualityResult.cleanFaceCount.toString()
        )
        StatItem(
            label = "Quality",
            value = "${(qualityResult.qualityScore * 100).toInt()}%"
        )
    }
}

@Composable
private fun StatItem(label: String, value: String) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = value,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold
        )
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * Build model name preview
 */
private fun buildModelName(name: String, ageText: String, year: String): String {
    return when {
        ageText.isNotBlank() -> "${name}_Age_${ageText}"
        else -> "${name}_${year}"
    }
}