package com.placeholder.sherpai2.ui.trainingprep

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.placeholder.sherpai2.ui.rollingscan.RollingScanModeDialog

/**
 * ImageSelectorScreen - WITH ROLLING SCAN INTEGRATION
 *
 * ENHANCED FEATURES:
 * ✅ Smart filtering (photos with faces)
 * ✅ Rolling Scan integration (NEW!)
 * ✅ Same signature as original
 * ✅ Drop-in replacement
 *
 * FLOW:
 * 1. User selects 3-5 photos
 * 2. RollingScanModeDialog appears
 * 3. User can:
 *    - Use Rolling Scan (recommended) → Navigate to Rolling Scan
 *    - Continue with current → Call onImagesSelected
 *    - Go back → Stay on selector
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageSelectorScreen(
    onImagesSelected: (List<Uri>) -> Unit,
    // NEW: Optional callback for Rolling Scan navigation
    // If null, Rolling Scan option is hidden
    onLaunchRollingScan: ((seedImageIds: List<String>) -> Unit)? = null
) {
    val viewModel: ImageSelectorViewModel = hiltViewModel()
    val faceTaggedUris by viewModel.faceTaggedImageUris.collectAsStateWithLifecycle()

    var selectedImages by remember { mutableStateOf<List<Uri>>(emptyList()) }
    var onlyShowFaceImages by remember { mutableStateOf(true) }
    var showRollingScanDialog by remember { mutableStateOf(false) } // NEW!
    val scrollState = rememberScrollState()

    val photoPicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetMultipleContents()
    ) { uris ->
        if (uris.isNotEmpty()) {
            // Filter to only face-tagged images if toggle is on
            selectedImages = if (onlyShowFaceImages && faceTaggedUris.isNotEmpty()) {
                uris.filter { it.toString() in faceTaggedUris }
            } else {
                uris
            }

            // NEW: Show Rolling Scan dialog if:
            // - Rolling Scan is available (callback provided)
            // - User selected 3-10 photos (sweet spot)
            if (onLaunchRollingScan != null && selectedImages.size in 3..10) {
                showRollingScanDialog = true
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Select Training Photos") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(scrollState)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {

            // Smart filtering card
            if (faceTaggedUris.isNotEmpty()) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.tertiaryContainer
                    ),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Row(
                                horizontalArrangement = Arrangement.spacedBy(8.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.AutoFixHigh,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.tertiary
                                )
                                Text(
                                    "Smart Filtering",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                            Spacer(Modifier.height(4.dp))
                            Text(
                                "Only show photos with detected faces (${faceTaggedUris.size} available)",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.8f)
                            )
                        }

                        Switch(
                            checked = onlyShowFaceImages,
                            onCheckedChange = { onlyShowFaceImages = it }
                        )
                    }
                }
            }

            // Gradient header with tips
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                ),
                shape = RoundedCornerShape(16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(20.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Surface(
                            shape = RoundedCornerShape(12.dp),
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(48.dp)
                        ) {
                            Box(contentAlignment = Alignment.Center) {
                                Icon(
                                    Icons.Default.PhotoCamera,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.onPrimary,
                                    modifier = Modifier.size(28.dp)
                                )
                            }
                        }

                        Column {
                            Text(
                                // NEW: Changed text if Rolling Scan available
                                if (onLaunchRollingScan != null) "Quick Start" else "Training Tips",
                                style = MaterialTheme.typography.titleLarge,
                                fontWeight = FontWeight.Bold
                            )
                            Text(
                                // NEW: Changed text if Rolling Scan available
                                if (onLaunchRollingScan != null)
                                    "Pick a few photos, we'll help find more"
                                else
                                    "More photos = better recognition",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f)
                            )
                        }
                    }

                    Spacer(Modifier.height(4.dp))

                    // NEW: Different tips if Rolling Scan available
                    if (onLaunchRollingScan != null) {
                        TipItem("✓ Start with just 3-5 good photos", true)
                        TipItem("✓ AI will find similar ones automatically", true)
                        TipItem("✓ Or select all 20-30 manually if you prefer", true)
                    } else {
                        TipItem("✓ Select 20-30 photos for best results", true)
                        TipItem("✓ Include different angles and lighting", true)
                        TipItem("✓ Mix expressions (smile, neutral, laugh)", true)
                        TipItem("✓ With/without glasses if applicable", true)
                        TipItem("✗ Avoid blurry or very dark photos", false)
                    }
                }
            }

            // Progress indicator
            AnimatedVisibility(selectedImages.isNotEmpty()) {
                ProgressCard(selectedImages.size)
            }

            // Select photos button
            Button(
                onClick = { photoPicker.launch("image/*") },
                modifier = Modifier.fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                ),
                contentPadding = PaddingValues(vertical = 16.dp)
            ) {
                Icon(Icons.Default.AddPhotoAlternate, contentDescription = null)
                Spacer(Modifier.width(8.dp))
                Text(
                    // NEW: Different text if Rolling Scan available
                    if (onLaunchRollingScan != null)
                        "Pick Seed Photos"
                    else
                        "Select Photos",
                    style = MaterialTheme.typography.titleMedium
                )
            }

            // Continue button (only if photos selected)
            AnimatedVisibility(selectedImages.isNotEmpty()) {
                Button(
                    onClick = { onImagesSelected(selectedImages) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.secondary
                    ),
                    contentPadding = PaddingValues(vertical = 16.dp)
                ) {
                    Icon(Icons.Default.Check, contentDescription = null)
                    Spacer(Modifier.width(8.dp))
                    Text(
                        "Continue with ${selectedImages.size} photos",
                        style = MaterialTheme.typography.titleMedium
                    )
                }
            }

            // Minimum warning
            if (selectedImages.isNotEmpty() && selectedImages.size < 15) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Warning,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.error
                        )
                        Column {
                            Text(
                                "Need at least 15 photos",
                                style = MaterialTheme.typography.titleSmall,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                            Text(
                                "You have ${selectedImages.size}. Select ${15 - selectedImages.size} more.",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.8f)
                            )
                        }
                    }
                }
            }

            // Bottom spacing
            Spacer(Modifier.height(32.dp))
        }
    }

    // NEW: Rolling Scan Mode Dialog
    if (showRollingScanDialog && selectedImages.isNotEmpty() && onLaunchRollingScan != null) {
        RollingScanModeDialog(
            currentPhotoCount = selectedImages.size,
            onUseRollingScan = {
                showRollingScanDialog = false

                // Convert URIs to image IDs
                // Note: Using URI strings as IDs for now
                // RollingScanViewModel will convert to actual IDs
                val seedImageIds = selectedImages.map { it.toString() }
                onLaunchRollingScan(seedImageIds)
            },
            onContinueWithCurrent = {
                showRollingScanDialog = false
                onImagesSelected(selectedImages)
            },
            onDismiss = {
                showRollingScanDialog = false
                // Keep selection, user can re-pick or continue
            }
        )
    }
}

@Composable
private fun TipItem(text: String, isGood: Boolean) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.Top
    ) {
        Icon(
            if (isGood) Icons.Default.CheckCircle else Icons.Default.Cancel,
            contentDescription = null,
            modifier = Modifier.size(18.dp),
            tint = if (isGood) {
                MaterialTheme.colorScheme.primary
            } else {
                MaterialTheme.colorScheme.error
            }
        )
        Text(
            text = text,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onPrimaryContainer
        )
    }
}

@Composable
private fun ProgressCard(photoCount: Int) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = when {
                photoCount >= 25 -> MaterialTheme.colorScheme.primaryContainer
                photoCount >= 20 -> MaterialTheme.colorScheme.tertiaryContainer
                else -> MaterialTheme.colorScheme.surfaceVariant
            }
        ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = "$photoCount photos selected",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = when {
                            photoCount >= 30 -> "Excellent! Maximum diversity"
                            photoCount >= 25 -> "Great! Very good coverage"
                            photoCount >= 20 -> "Good! Should work well"
                            photoCount >= 15 -> "Acceptable - more is better"
                            else -> "Need ${15 - photoCount} more"
                        },
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                Surface(
                    shape = RoundedCornerShape(12.dp),
                    color = when {
                        photoCount >= 25 -> MaterialTheme.colorScheme.primary
                        photoCount >= 20 -> MaterialTheme.colorScheme.tertiary
                        photoCount >= 15 -> MaterialTheme.colorScheme.secondary
                        else -> MaterialTheme.colorScheme.outline
                    },
                    modifier = Modifier.size(56.dp)
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Text(
                            text = when {
                                photoCount >= 25 -> "★"
                                photoCount >= 20 -> "✓"
                                photoCount >= 15 -> "○"
                                else -> "..."
                            },
                            style = MaterialTheme.typography.headlineMedium,
                            color = Color.White
                        )
                    }
                }
            }

            // Progress bar
            LinearProgressIndicator(
                progress = { (photoCount / 30f).coerceAtMost(1f) },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(8.dp),
                color = when {
                    photoCount >= 25 -> MaterialTheme.colorScheme.primary
                    photoCount >= 20 -> MaterialTheme.colorScheme.tertiary
                    else -> MaterialTheme.colorScheme.secondary
                },
                trackColor = MaterialTheme.colorScheme.surfaceVariant,
            )

            // Expected accuracy
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    "Expected accuracy:",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    when {
                        photoCount >= 30 -> "90-95%"
                        photoCount >= 25 -> "85-90%"
                        photoCount >= 20 -> "80-85%"
                        photoCount >= 15 -> "75-80%"
                        else -> "< 75%"
                    },
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.Bold,
                    color = when {
                        photoCount >= 25 -> MaterialTheme.colorScheme.primary
                        photoCount >= 20 -> MaterialTheme.colorScheme.tertiary
                        else -> MaterialTheme.colorScheme.secondary
                    }
                )
            }
        }
    }
}