package com.placeholder.sherpai2.ui.trainingprep

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
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.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog

/**
 * IMPROVED NameInputDialog - Better centered, cleaner layout
 *
 * Fixes:
 * - Centered dialog with proper constraints
 * - Better spacing and padding
 * - Clearer visual hierarchy
 * - Improved error state handling
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImprovedNameInputDialog(
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit,
    trainingState: TrainingState
) {
    var personName by remember { mutableStateOf("") }
    val isError = trainingState is TrainingState.Error
    val isProcessing = trainingState is TrainingState.Processing

    Dialog(
        onDismissRequest = {
            if (!isProcessing) {
                onDismiss()
            }
        }
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth(0.9f) // 90% of screen width
                .wrapContentHeight(),
            shape = RoundedCornerShape(24.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // Icon
                Surface(
                    shape = RoundedCornerShape(16.dp),
                    color = if (isError) {
                        MaterialTheme.colorScheme.errorContainer
                    } else {
                        MaterialTheme.colorScheme.primaryContainer
                    },
                    modifier = Modifier.size(72.dp)
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Icon(
                            if (isError) Icons.Default.Warning else Icons.Default.Face,
                            contentDescription = null,
                            modifier = Modifier.size(40.dp),
                            tint = if (isError) {
                                MaterialTheme.colorScheme.error
                            } else {
                                MaterialTheme.colorScheme.primary
                            }
                        )
                    }
                }

                // Title
                Text(
                    text = if (isError) "Training Error" else "Who is this?",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )

                // Error message or description
                if (isError) {
                    val error = trainingState as TrainingState.Error
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            horizontalArrangement = Arrangement.spacedBy(12.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.Error,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error
                            )
                            Text(
                                text = error.message,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                        }
                    }
                } else {
                    Text(
                        text = "Enter the name of the person in these training images. This will help you find their photos later.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                // Name input field
                OutlinedTextField(
                    value = personName,
                    onValueChange = { personName = it },
                    label = { Text("Person's Name") },
                    placeholder = { Text("e.g., John Doe") },
                    singleLine = true,
                    enabled = !isProcessing,
                    keyboardOptions = KeyboardOptions(
                        capitalization = KeyboardCapitalization.Words,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(
                        onDone = {
                            if (personName.isNotBlank() && !isProcessing) {
                                onConfirm(personName.trim())
                            }
                        }
                    ),
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = MaterialTheme.colorScheme.primary,
                        unfocusedBorderColor = MaterialTheme.colorScheme.outline
                    )
                )

                // Action buttons
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // Cancel button
                    if (!isProcessing) {
                        OutlinedButton(
                            onClick = onDismiss,
                            modifier = Modifier.weight(1f),
                            shape = RoundedCornerShape(12.dp),
                            contentPadding = PaddingValues(vertical = 14.dp)
                        ) {
                            Text("Cancel")
                        }
                    }

                    // Confirm button
                    Button(
                        onClick = { onConfirm(personName.trim()) },
                        enabled = personName.isNotBlank() && !isProcessing,
                        modifier = Modifier.weight(if (isProcessing) 1f else 1f),
                        shape = RoundedCornerShape(12.dp),
                        contentPadding = PaddingValues(vertical = 14.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (isError) {
                                MaterialTheme.colorScheme.error
                            } else {
                                MaterialTheme.colorScheme.primary
                            }
                        )
                    ) {
                        if (isProcessing) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(20.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                            Spacer(modifier = Modifier.width(12.dp))
                            Text("Training...")
                        } else {
                            Icon(
                                if (isError) Icons.Default.Refresh else Icons.Default.Check,
                                contentDescription = null,
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(if (isError) "Try Again" else "Start Training")
                        }
                    }
                }
            }
        }
    }
}

/**
 * Alternative: Use this version in ScanResultsScreen.kt
 *
 * Replace the existing NameInputDialog function (lines 154-257) with:
 *
 * @Composable
 * private fun NameInputDialog(
 *     onDismiss: () -> Unit,
 *     onConfirm: (String) -> Unit,
 *     trainingState: TrainingState
 * ) {
 *     ImprovedNameInputDialog(
 *         onDismiss = onDismiss,
 *         onConfirm = onConfirm,
 *         trainingState = trainingState
 *     )
 * }
 */