package com.placeholder.sherpai2.ui.discover

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Storage
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.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.placeholder.sherpai2.domain.clustering.ClusterQualityAnalyzer

/**
 * DiscoverPeopleScreen - WITH SETTINGS SUPPORT
 *
 * NEW FEATURES:
 * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 * ✅ Discovery settings card with quality sliders
 * ✅ Retry button in naming dialog
 * ✅ Cache building progress UI
 * ✅ Settings affect clustering behavior
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DiscoverPeopleScreen(
    viewModel: DiscoverPeopleViewModel = hiltViewModel(),
    onNavigateBack: () -> Unit = {}
) {
    val uiState by viewModel.uiState.collectAsState()
    val qualityAnalyzer = remember { ClusterQualityAnalyzer() }

    // NEW: Settings state
    var settings by remember { mutableStateOf(DiscoverySettings.DEFAULT) }

    Box(modifier = Modifier.fillMaxSize()) {
        when (val state = uiState) {
            // ===== IDLE STATE (START HERE) =====
            is DiscoverUiState.Idle -> {
                IdleStateWithSettings(
                    settings = settings,
                    onSettingsChange = { settings = it },
                    onStartDiscovery = { viewModel.startDiscovery(settings) }
                )
            }

            // ===== NEW: BUILDING CACHE (FIRST-TIME SETUP) =====
            is DiscoverUiState.BuildingCache -> {
                BuildingCacheContent(
                    progress = state.progress,
                    total = state.total,
                    message = state.message
                )
            }

            // ===== CLUSTERING IN PROGRESS =====
            is DiscoverUiState.Clustering -> {
                ClusteringProgressContent(
                    progress = state.progress,
                    total = state.total,
                    message = state.message
                )
            }

            // ===== CLUSTERS READY FOR NAMING =====
            is DiscoverUiState.NamingReady -> {
                ClusterGridScreen(
                    result = state.result,
                    onSelectCluster = { cluster ->
                        viewModel.selectCluster(cluster)
                    },
                    qualityAnalyzer = qualityAnalyzer
                )
            }

            // ===== ANALYZING CLUSTER QUALITY =====
            is DiscoverUiState.AnalyzingCluster -> {
                LoadingContent(message = "Analyzing cluster quality...")
            }

            // ===== NAMING A CLUSTER (SHOW DIALOG) =====
            is DiscoverUiState.NamingCluster -> {
                ClusterGridScreen(
                    result = state.result,
                    onSelectCluster = { /* Disabled while dialog open */ },
                    qualityAnalyzer = qualityAnalyzer
                )

                NamingDialog(
                    cluster = state.selectedCluster,
                    suggestedSiblings = state.suggestedSiblings,
                    onConfirm = { name, dateOfBirth, isChild, selectedSiblings ->
                        viewModel.confirmClusterName(
                            cluster = state.selectedCluster,
                            name = name,
                            dateOfBirth = dateOfBirth,
                            isChild = isChild,
                            selectedSiblings = selectedSiblings
                        )
                    },
                    onRetry = { viewModel.retryDiscovery() },  // NEW!
                    onDismiss = {
                        viewModel.cancelNaming()
                    },
                    qualityAnalyzer = qualityAnalyzer
                )
            }

            // ===== TRAINING IN PROGRESS =====
            is DiscoverUiState.Training -> {
                TrainingProgressContent(
                    stage = state.stage,
                    progress = state.progress,
                    total = state.total
                )
            }

            // ===== VALIDATION PREVIEW =====
            is DiscoverUiState.ValidationPreview -> {
                ValidationPreviewScreen(
                    personName = state.personName,
                    validationResult = state.validationResult,
                    onMarkFeedback = { feedbackMap ->
                        viewModel.submitFeedback(state.cluster, feedbackMap)
                    },
                    onRequestRefinement = {
                        viewModel.requestRefinement(state.cluster)
                    },
                    onApprove = {
                        viewModel.acceptValidationAndFinish()
                    },
                    onReject = {
                        viewModel.requestRefinement(state.cluster)
                    }
                )
            }

            // ===== REFINEMENT NEEDED =====
            is DiscoverUiState.RefinementNeeded -> {
                RefinementNeededContent(
                    recommendation = state.recommendation,
                    currentIteration = state.currentIteration,
                    onRefine = {
                        viewModel.requestRefinement(state.cluster)
                    },
                    onSkip = {
                        viewModel.skipRefinement()
                    }
                )
            }

            // ===== REFINING IN PROGRESS =====
            is DiscoverUiState.Refining -> {
                RefiningProgressContent(
                    iteration = state.iteration,
                    message = state.message
                )
            }

            // ===== COMPLETE =====
            is DiscoverUiState.Complete -> {
                CompleteStateContent(
                    message = state.message,
                    onDone = onNavigateBack,
                    onDiscoverMore = { viewModel.retryDiscovery() }
                )
            }

            // ===== NO PEOPLE FOUND =====
            is DiscoverUiState.NoPeopleFound -> {
                ErrorStateContent(
                    title = "No People Found",
                    message = state.message,
                    onRetry = { viewModel.retryDiscovery() },
                    onBack = onNavigateBack
                )
            }

            // ===== ERROR =====
            is DiscoverUiState.Error -> {
                ErrorStateContent(
                    title = "Error",
                    message = state.message,
                    onRetry = { viewModel.retryDiscovery() },
                    onBack = onNavigateBack
                )
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════
// IDLE STATE WITH SETTINGS
// ═══════════════════════════════════════════════════════════

@Composable
private fun IdleStateWithSettings(
    settings: DiscoverySettings,
    onSettingsChange: (DiscoverySettings) -> Unit,
    onStartDiscovery: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = Icons.Default.Person,
            contentDescription = null,
            modifier = Modifier.size(120.dp),
            tint = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(32.dp))

        Text(
            text = "Automatically find and organize people in your photo library",
            style = MaterialTheme.typography.headlineSmall,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurface
        )

        Spacer(modifier = Modifier.height(32.dp))

        // NEW: Settings Card
        DiscoverySettingsCard(
            settings = settings,
            onSettingsChange = onSettingsChange
        )

        Spacer(modifier = Modifier.height(24.dp))

        Button(
            onClick = onStartDiscovery,
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
        ) {
            Text(
                text = "Start Discovery",
                style = MaterialTheme.typography.titleMedium
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "This will analyze faces in your photos and group similar faces together",
            style = MaterialTheme.typography.bodySmall,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

// ═══════════════════════════════════════════════════════════
// BUILDING CACHE CONTENT
// ═══════════════════════════════════════════════════════════

@Composable
private fun BuildingCacheContent(
    progress: Int,
    total: Int,
    message: String
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = Icons.Default.Storage,
            contentDescription = null,
            modifier = Modifier.size(80.dp),
            tint = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(32.dp))

        Text(
            text = "Building Cache",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center
        )

        Spacer(modifier = Modifier.height(16.dp))

        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer
            ),
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = message,
                    style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        if (total > 0) {
            LinearProgressIndicator(
                progress = { progress.toFloat() / total.toFloat() },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(12.dp)
            )

            Spacer(modifier = Modifier.height(12.dp))

            Text(
                text = "$progress / $total photos analyzed",
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.primary
            )

            Spacer(modifier = Modifier.height(8.dp))

            val percentComplete = (progress.toFloat() / total.toFloat() * 100).toInt()
            Text(
                text = "$percentComplete% complete",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        } else {
            CircularProgressIndicator(
                modifier = Modifier.size(64.dp)
            )
        }

        Spacer(modifier = Modifier.height(32.dp))

        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.secondaryContainer
            ),
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "ℹ️ What's happening?",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "We're analyzing your photo library once to identify which photos contain faces. " +
                            "This speeds up future discoveries by 95%!\n\n" +
                            "This only happens once and will make all future discoveries instant.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════
// CLUSTERING PROGRESS
// ═══════════════════════════════════════════════════════════

@Composable
private fun ClusteringProgressContent(
    progress: Int,
    total: Int,
    message: String
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(64.dp)
        )

        Spacer(modifier = Modifier.height(32.dp))

        Text(
            text = message,
            style = MaterialTheme.typography.titleMedium,
            textAlign = TextAlign.Center
        )

        Spacer(modifier = Modifier.height(16.dp))

        if (total > 0) {
            LinearProgressIndicator(
                progress = { progress.toFloat() / total.toFloat() },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(8.dp)
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "$progress / $total",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════
// TRAINING PROGRESS
// ═══════════════════════════════════════════════════════════

@Composable
private fun TrainingProgressContent(
    stage: String,
    progress: Int,
    total: Int
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(64.dp)
        )

        Spacer(modifier = Modifier.height(32.dp))

        Text(
            text = stage,
            style = MaterialTheme.typography.titleMedium,
            textAlign = TextAlign.Center
        )

        if (total > 0) {
            Spacer(modifier = Modifier.height(16.dp))

            LinearProgressIndicator(
                progress = { progress.toFloat() / total.toFloat() },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(8.dp)
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "$progress / $total",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════
// REFINEMENT NEEDED
// ═══════════════════════════════════════════════════════════

@Composable
private fun RefinementNeededContent(
    recommendation: com.placeholder.sherpai2.domain.clustering.RefinementRecommendation,
    currentIteration: Int,
    onRefine: () -> Unit,
    onSkip: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = Icons.Default.Person,
            contentDescription = null,
            modifier = Modifier.size(80.dp),
            tint = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(24.dp))

        Text(
            text = "Refinement Recommended",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(16.dp))

        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.errorContainer
            )
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = recommendation.reason,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onErrorContainer
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "Iteration: $currentIteration",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(32.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = onSkip,
                modifier = Modifier.weight(1f)
            ) {
                Text("Skip")
            }

            Button(
                onClick = onRefine,
                modifier = Modifier.weight(1f)
            ) {
                Text("Refine Cluster")
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════
// REFINING PROGRESS
// ═══════════════════════════════════════════════════════════

@Composable
private fun RefiningProgressContent(
    iteration: Int,
    message: String
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(64.dp)
        )

        Spacer(modifier = Modifier.height(32.dp))

        Text(
            text = "Refining Cluster",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = message,
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "Iteration $iteration",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

// ═══════════════════════════════════════════════════════════
// LOADING CONTENT
// ═══════════════════════════════════════════════════════════

@Composable
private fun LoadingContent(message: String) {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator()
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = message)
    }
}

// ═══════════════════════════════════════════════════════════
// COMPLETE STATE
// ═══════════════════════════════════════════════════════════

@Composable
private fun CompleteStateContent(
    message: String,
    onDone: () -> Unit,
    onDiscoverMore: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "🎉",
            style = MaterialTheme.typography.displayLarge
        )

        Spacer(modifier = Modifier.height(24.dp))

        Text(
            text = "Success!",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = message,
            style = MaterialTheme.typography.bodyLarge,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(32.dp))

        Button(
            onClick = onDone,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("Done")
        }

        Spacer(modifier = Modifier.height(12.dp))

        OutlinedButton(
            onClick = onDiscoverMore,
            modifier = Modifier.fillMaxWidth()
        ) {
            Icon(
                imageVector = Icons.Default.Refresh,
                contentDescription = null,
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.width(8.dp))
            Text("Discover More People")
        }
    }
}

// ═══════════════════════════════════════════════════════════
// ERROR STATE
// ═══════════════════════════════════════════════════════════

@Composable
private fun ErrorStateContent(
    title: String,
    message: String,
    onRetry: () -> Unit,
    onBack: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "⚠️",
            style = MaterialTheme.typography.displayLarge
        )

        Spacer(modifier = Modifier.height(24.dp))

        Text(
            text = title,
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = message,
            style = MaterialTheme.typography.bodyLarge,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(32.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = onBack,
                modifier = Modifier.weight(1f)
            ) {
                Text("Back")
            }

            Button(
                onClick = onRetry,
                modifier = Modifier.weight(1f)
            ) {
                Text("Retry")
            }
        }
    }
}