package com.placeholder.sherpai2.ui.trainingprep

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import android.net.Uri
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.FaceDetection
import androidx.compose.ui.graphics.Color
import com.google.mlkit.vision.face.FaceDetectorOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext

/**
 * MINIMAL FacePickerDialog - Optimized for batch processing 30-50 photos
 *
 * REMOVED CLUTTER:
 * - "Preview (tap to select)" header
 * - "Face will be used for training" info box
 * - "Face #" labels covering previews
 * - Original image preview
 *
 * IMPROVED:
 * - Larger face previews (1:1 aspect ratio)
 * - Clean checkmark overlay only
 * - Minimal text
 * - Fast workflow
 */
@Composable
fun FacePickerDialog(
    result: FaceDetectionHelper.FaceDetectionResult,
    onDismiss: () -> Unit,
    onFaceSelected: (Int, Bitmap) -> Unit
) {
    val context = LocalContext.current
    var selectedFaceIndex by remember { mutableStateOf(0) }
    var croppedFaces by remember { mutableStateOf<List<Bitmap>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    // Load and crop all faces - RE-DETECT to get accurate bounds
    LaunchedEffect(result) {
        isLoading = true
        errorMessage = null

        try {
            croppedFaces = withContext(Dispatchers.IO) {
                // Load the FULL resolution bitmap (no downsampling)
                val fullBitmap = loadFullResolutionBitmap(context, result.uri)

                if (fullBitmap == null) {
                    errorMessage = "Failed to load image"
                    return@withContext emptyList()
                }

                // Re-detect faces on the full resolution bitmap to get accurate bounds
                val accurateFaceBounds = detectFacesOnBitmap(fullBitmap)

                if (accurateFaceBounds.isEmpty()) {
                    // Fallback: try to use the original bounds with scaling
                    val scaledBounds = result.faceBounds.map { originalBounds ->
                        cropFaceFromBitmap(fullBitmap, originalBounds)
                    }
                    fullBitmap.recycle()
                    return@withContext scaledBounds
                }

                // Crop faces using accurate bounds
                val croppedList = accurateFaceBounds.map { bounds ->
                    cropFaceFromBitmap(fullBitmap, bounds)
                }

                // CRITICAL: Recycle AFTER all cropping is done
                fullBitmap.recycle()

                croppedList
            }

            if (croppedFaces.isEmpty() && errorMessage == null) {
                errorMessage = "No faces found in full resolution image"
            }

        } catch (e: Exception) {
            errorMessage = "Error processing faces: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false)
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth(0.92f)
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // Minimal header - just close button
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "${result.faceCount} faces",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )

                    IconButton(onClick = onDismiss) {
                        Icon(Icons.Default.Close, contentDescription = "Close")
                    }
                }

                if (isLoading) {
                    // Loading state - minimal
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(180.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                } else if (errorMessage != null) {
                    // Error state - minimal
                    Text(
                        text = errorMessage!!,
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodyMedium
                    )
                } else {
                    // CLEAN face grid - NO labels, NO text
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(10.dp)
                    ) {
                        croppedFaces.forEachIndexed { index, faceBitmap ->
                            CleanFaceCard(
                                faceBitmap = faceBitmap,
                                isSelected = selectedFaceIndex == index,
                                onClick = { selectedFaceIndex = index },
                                modifier = Modifier.weight(1f)
                            )
                        }
                    }
                }

                // Action buttons - minimal
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    TextButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Skip")
                    }

                    Button(
                        onClick = {
                            if (selectedFaceIndex < croppedFaces.size) {
                                onFaceSelected(selectedFaceIndex, croppedFaces[selectedFaceIndex])
                            }
                        },
                        enabled = !isLoading && croppedFaces.isNotEmpty(),
                        modifier = Modifier.weight(1f)
                    ) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(6.dp))
                        Text("Use")
                    }
                }
            }
        }
    }
}

/**
 * ULTRA-CLEAN face card - NO TEXT, just image + checkmark
 *
 * CHANGES:
 * - 1:1 aspect ratio (bigger!)
 * - NO "Face #" label
 * - Checkmark in corner only
 * - Minimal border
 */
@Composable
private fun CleanFaceCard(
    faceBitmap: Bitmap,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .aspectRatio(1f) // SQUARE = bigger previews!
            .clickable(onClick = onClick),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        ),
        border = if (isSelected)
            BorderStroke(3.dp, MaterialTheme.colorScheme.primary)
        else
            BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(
            defaultElevation = if (isSelected) 4.dp else 1.dp
        )
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            // Face image - FULL SIZE
            Image(
                bitmap = faceBitmap.asImageBitmap(),
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )

            // Checkmark in corner - ONLY if selected
            if (isSelected) {
                Surface(
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .padding(6.dp)
                        .size(32.dp),
                    shape = CircleShape,
                    color = MaterialTheme.colorScheme.primary,
                    shadowElevation = 4.dp
                ) {
                    Icon(
                        Icons.Default.CheckCircle,
                        contentDescription = "Selected",
                        modifier = Modifier
                            .padding(6.dp)
                            .size(20.dp),
                        tint = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
        }
    }
}

/**
 * Load full resolution bitmap WITHOUT downsampling
 */
private suspend fun loadFullResolutionBitmap(
    context: android.content.Context,
    uri: Uri
): Bitmap? = withContext(Dispatchers.IO) {
    try {
        val inputStream = context.contentResolver.openInputStream(uri)
        BitmapFactory.decodeStream(inputStream)?.also {
            inputStream?.close()
        }
    } catch (e: Exception) {
        null
    }
}

/**
 * Re-detect faces on full resolution bitmap to get accurate bounds
 */
private suspend fun detectFacesOnBitmap(bitmap: Bitmap): List<Rect> = withContext(Dispatchers.Default) {
    try {
        val options = FaceDetectorOptions.Builder()
            .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
            .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_NONE)
            .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE)
            .setMinFaceSize(0.10f)
            .build()

        val detector = FaceDetection.getClient(options)
        val image = InputImage.fromBitmap(bitmap, 0)
        val faces = detector.process(image).await()

        // Sort by size (largest first)
        faces.sortedByDescending { face ->
            face.boundingBox.width() * face.boundingBox.height()
        }.map { it.boundingBox }

    } catch (e: Exception) {
        emptyList()
    }
}

/**
 * Crop face from bitmap with padding
 */
private fun cropFaceFromBitmap(bitmap: Bitmap, faceBounds: Rect): Bitmap {
    // Add 20% padding around the face
    val padding = (faceBounds.width() * 0.2f).toInt()

    val left = (faceBounds.left - padding).coerceAtLeast(0)
    val top = (faceBounds.top - padding).coerceAtLeast(0)
    val right = (faceBounds.right + padding).coerceAtMost(bitmap.width)
    val bottom = (faceBounds.bottom + padding).coerceAtMost(bitmap.height)

    val width = right - left
    val height = bottom - top

    return Bitmap.createBitmap(bitmap, left, top, width, height)
}