package com.placeholder.sherpai2.ui.discover

import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
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.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import coil.compose.AsyncImage
import com.placeholder.sherpai2.data.local.entity.FeedbackType
import com.placeholder.sherpai2.domain.validation.ValidationScanResult
import com.placeholder.sherpai2.domain.validation.ValidationMatch
import kotlin.math.roundToInt

/**
 * ValidationPreviewScreen - User reviews validation results with swipe gestures
 *
 * FEATURES:
 * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 * ✅ Swipe right (✓) = Confirmed match
 * ✅ Swipe left (✗) = Rejected match
 * ✅ Tap = Mark uncertain (?)
 * ✅ Real-time feedback stats
 * ✅ Automatic refinement recommendation
 * ✅ Bottom bar with approve/reject/refine actions
 *
 * FLOW:
 * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 * 1. User swipes/taps to mark faces
 * 2. Feedback tracked in local state
 * 3. If >15% rejection → "Refine" button appears
 * 4. Approve → Sends feedback map to ViewModel
 * 5. Reject → Returns to previous screen
 * 6. Refine → Triggers cluster refinement
 */
@Composable
fun ValidationPreviewScreen(
    personName: String,
    validationResult: ValidationScanResult,
    onMarkFeedback: (Map<String, FeedbackType>) -> Unit = {},
    onRequestRefinement: () -> Unit = {},
    onApprove: () -> Unit,
    onReject: () -> Unit,
    modifier: Modifier = Modifier
) {
    // Get sample images from validation result matches
    val sampleMatches = remember(validationResult) {
        validationResult.matches.take(24) // Show up to 24 faces
    }

    // Track feedback for each image (imageId -> FeedbackType)
    var feedbackMap by remember {
        mutableStateOf<Map<String, FeedbackType>>(emptyMap())
    }

    // Calculate feedback statistics
    val confirmedCount = feedbackMap.count { it.value == FeedbackType.CONFIRMED_MATCH }
    val rejectedCount = feedbackMap.count { it.value == FeedbackType.REJECTED_MATCH }
    val uncertainCount = feedbackMap.count { it.value == FeedbackType.UNCERTAIN }
    val reviewedCount = feedbackMap.size
    val totalCount = sampleMatches.size

    // Determine if refinement is recommended
    val rejectionRatio = if (reviewedCount > 0) {
        rejectedCount.toFloat() / reviewedCount.toFloat()
    } else {
        0f
    }
    val shouldRefine = rejectionRatio > 0.15f && rejectedCount >= 2

    Scaffold(
        bottomBar = {
            ValidationBottomBar(
                confirmedCount = confirmedCount,
                rejectedCount = rejectedCount,
                uncertainCount = uncertainCount,
                reviewedCount = reviewedCount,
                totalCount = totalCount,
                shouldRefine = shouldRefine,
                onApprove = {
                    onMarkFeedback(feedbackMap)
                    onApprove()
                },
                onReject = onReject,
                onRefine = {
                    onMarkFeedback(feedbackMap)
                    onRequestRefinement()
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            // Header
            Text(
                text = "Validate \"$personName\"",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )

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

            // Instructions
            InstructionsCard()

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

            // Feedback stats
            FeedbackStatsCard(
                confirmedCount = confirmedCount,
                rejectedCount = rejectedCount,
                uncertainCount = uncertainCount,
                reviewedCount = reviewedCount,
                totalCount = totalCount
            )

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

            // Grid of faces to review
            LazyVerticalGrid(
                columns = GridCells.Fixed(3),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.weight(1f)
            ) {
                items(
                    items = sampleMatches,
                    key = { match -> match.imageId }
                ) { match ->
                    SwipeableFaceCard(
                        match = match,
                        currentFeedback = feedbackMap[match.imageId],
                        onFeedbackChange = { feedback ->
                            feedbackMap = feedbackMap.toMutableMap().apply {
                                put(match.imageId, feedback)
                            }
                        }
                    )
                }
            }
        }
    }
}

/**
 * Swipeable face card with visual feedback indicators
 */
@Composable
private fun SwipeableFaceCard(
    match: ValidationMatch,
    currentFeedback: FeedbackType?,
    onFeedbackChange: (FeedbackType) -> Unit
) {
    var offsetX by remember { mutableFloatStateOf(0f) }
    var isDragging by remember { mutableStateOf(false) }

    val scale by animateFloatAsState(
        targetValue = if (isDragging) 1.1f else 1f,
        label = "scale"
    )

    Box(
        modifier = Modifier
            .aspectRatio(1f)
            .scale(scale)
            .zIndex(if (isDragging) 1f else 0f)
    ) {
        // Face image with border color based on feedback
        AsyncImage(
            model = Uri.parse(match.imageUri),
            contentDescription = "Face",
            modifier = Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(12.dp))
                .border(
                    width = 3.dp,
                    color = when (currentFeedback) {
                        FeedbackType.CONFIRMED_MATCH -> Color(0xFF4CAF50) // Green
                        FeedbackType.REJECTED_MATCH -> Color(0xFFF44336) // Red
                        FeedbackType.UNCERTAIN -> Color(0xFFFF9800) // Orange
                        else -> MaterialTheme.colorScheme.outline
                    },
                    shape = RoundedCornerShape(12.dp)
                )
                .offset { IntOffset(offsetX.roundToInt(), 0) }
                .pointerInput(Unit) {
                    detectDragGestures(
                        onDragStart = {
                            isDragging = true
                        },
                        onDrag = { _, dragAmount ->
                            offsetX += dragAmount.x
                        },
                        onDragEnd = {
                            isDragging = false

                            // Determine feedback based on swipe direction
                            when {
                                offsetX > 100 -> {
                                    onFeedbackChange(FeedbackType.CONFIRMED_MATCH)
                                }
                                offsetX < -100 -> {
                                    onFeedbackChange(FeedbackType.REJECTED_MATCH)
                                }
                            }

                            // Reset position
                            offsetX = 0f
                        },
                        onDragCancel = {
                            isDragging = false
                            offsetX = 0f
                        }
                    )
                }
                .clickable {
                    // Tap to toggle uncertain
                    val newFeedback = when (currentFeedback) {
                        FeedbackType.UNCERTAIN -> null
                        else -> FeedbackType.UNCERTAIN
                    }
                    if (newFeedback != null) {
                        onFeedbackChange(newFeedback)
                    }
                },
            contentScale = ContentScale.Crop
        )

        // Confidence badge (top-left)
        Surface(
            modifier = Modifier
                .align(Alignment.TopStart)
                .padding(4.dp),
            shape = RoundedCornerShape(4.dp),
            color = Color.Black.copy(alpha = 0.6f)
        ) {
            Text(
                text = "${(match.confidence * 100).toInt()}%",
                modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                style = MaterialTheme.typography.labelSmall,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }

        // Feedback indicator overlay (top-right)
        if (currentFeedback != null) {
            Surface(
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(4.dp),
                shape = CircleShape,
                color = when (currentFeedback) {
                    FeedbackType.CONFIRMED_MATCH -> Color(0xFF4CAF50)
                    FeedbackType.REJECTED_MATCH -> Color(0xFFF44336)
                    FeedbackType.UNCERTAIN -> Color(0xFFFF9800)
                    else -> Color.Transparent
                },
                shadowElevation = 2.dp
            ) {
                Icon(
                    imageVector = when (currentFeedback) {
                        FeedbackType.CONFIRMED_MATCH -> Icons.Default.Check
                        FeedbackType.REJECTED_MATCH -> Icons.Default.Close
                        FeedbackType.UNCERTAIN -> Icons.Default.Warning
                        else -> Icons.Default.Info
                    },
                    contentDescription = currentFeedback.name,
                    tint = Color.White,
                    modifier = Modifier
                        .size(32.dp)
                        .padding(6.dp)
                )
            }
        }

        // Swipe hint during drag
        if (isDragging) {
            SwipeDragHint(offsetX = offsetX)
        }
    }
}

/**
 * Swipe drag hint overlay
 */
@Composable
private fun BoxScope.SwipeDragHint(offsetX: Float) {
    val hintText = when {
        offsetX > 50 -> "✓ Correct"
        offsetX < -50 -> "✗ Incorrect"
        else -> "Keep swiping"
    }

    val hintColor = when {
        offsetX > 50 -> Color(0xFF4CAF50)
        offsetX < -50 -> Color(0xFFF44336)
        else -> Color.Gray
    }

    Surface(
        modifier = Modifier
            .align(Alignment.BottomCenter)
            .padding(8.dp),
        shape = RoundedCornerShape(4.dp),
        color = hintColor.copy(alpha = 0.9f)
    ) {
        Text(
            text = hintText,
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
            style = MaterialTheme.typography.labelSmall,
            color = Color.White,
            fontWeight = FontWeight.Bold
        )
    }
}

/**
 * Instructions card showing gesture controls
 */
@Composable
private fun InstructionsCard() {
    Card(
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        )
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Info,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onPrimaryContainer
            )

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

            Column {
                Text(
                    text = "Review Detected Faces",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Swipe right ✅ for correct, left ❌ for incorrect, tap ❓ for uncertain",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
            }
        }
    }
}

/**
 * Feedback statistics card
 */
@Composable
private fun FeedbackStatsCard(
    confirmedCount: Int,
    rejectedCount: Int,
    uncertainCount: Int,
    reviewedCount: Int,
    totalCount: Int
) {
    Card {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            FeedbackStat(
                icon = Icons.Default.Check,
                color = Color(0xFF4CAF50),
                count = confirmedCount,
                label = "Correct"
            )

            FeedbackStat(
                icon = Icons.Default.Close,
                color = Color(0xFFF44336),
                count = rejectedCount,
                label = "Incorrect"
            )

            FeedbackStat(
                icon = Icons.Default.Warning,
                color = Color(0xFFFF9800),
                count = uncertainCount,
                label = "Uncertain"
            )
        }

        val progressValue = if (totalCount > 0) {
            reviewedCount.toFloat() / totalCount.toFloat()
        } else {
            0f
        }

        LinearProgressIndicator(
            progress = { progressValue },
            modifier = Modifier
                .fillMaxWidth()
                .height(4.dp)
        )
    }
}

/**
 * Individual feedback statistic item
 */
@Composable
private fun FeedbackStat(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    color: Color,
    count: Int,
    label: String
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Surface(
            shape = CircleShape,
            color = color.copy(alpha = 0.2f)
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = color,
                modifier = Modifier
                    .size(40.dp)
                    .padding(8.dp)
            )
        }

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

        Text(
            text = count.toString(),
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold
        )

        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * Bottom action bar with approve/reject/refine buttons
 */
@Composable
private fun ValidationBottomBar(
    confirmedCount: Int,
    rejectedCount: Int,
    uncertainCount: Int,
    reviewedCount: Int,
    totalCount: Int,
    shouldRefine: Boolean,
    onApprove: () -> Unit,
    onReject: () -> Unit,
    onRefine: () -> Unit
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shadowElevation = 8.dp
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // Refinement warning banner
            AnimatedVisibility(visible = shouldRefine) {
                RefinementWarningBanner(
                    rejectedCount = rejectedCount,
                    reviewedCount = reviewedCount,
                    onRefine = onRefine
                )
            }

            // Main action buttons
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                OutlinedButton(
                    onClick = onReject,
                    modifier = Modifier.weight(1f)
                ) {
                    Icon(Icons.Default.Close, contentDescription = null)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Reject")
                }

                Button(
                    onClick = onApprove,
                    modifier = Modifier.weight(1f),
                    enabled = confirmedCount > 0 || (reviewedCount == 0 && totalCount > 6)
                ) {
                    Icon(Icons.Default.Check, contentDescription = null)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Approve")
                }
            }

            // Review progress text
            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = if (reviewedCount == 0) {
                    "Review faces above or approve to continue"
                } else {
                    "Reviewed $reviewedCount of $totalCount faces"
                },
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}

/**
 * Refinement warning banner component
 */
@Composable
private fun RefinementWarningBanner(
    rejectedCount: Int,
    reviewedCount: Int,
    onRefine: () -> Unit
) {
    Column {
        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.errorContainer
            ),
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier.padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Default.Warning,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onErrorContainer
                )

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

                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "High Rejection Rate",
                        style = MaterialTheme.typography.titleSmall,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                    Text(
                        text = "${(rejectedCount.toFloat() / reviewedCount.toFloat() * 100).toInt()}% rejected. Consider refining the cluster.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                }

                Button(
                    onClick = onRefine,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("Refine")
                }
            }
        }

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