package com.placeholder.sherpai2.ui.discover

import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.Check
import androidx.compose.material.icons.filled.Warning
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.placeholder.sherpai2.domain.clustering.ClusterQualityAnalyzer
import com.placeholder.sherpai2.domain.clustering.ClusterQualityTier
import com.placeholder.sherpai2.domain.clustering.ClusteringResult
import com.placeholder.sherpai2.domain.clustering.FaceCluster

/**
 * ClusterGridScreen - Shows all discovered clusters in 2x2 grid
 *
 * Each cluster card shows:
 * - 2x2 grid of representative faces
 * - Photo count
 * - Quality badge (Excellent/Good/Poor)
 * - Tap to name
 *
 * IMPROVEMENTS:
 * - ✅ Quality badges for each cluster
 * - ✅ Visual indicators for trainable vs non-trainable clusters
 * - ✅ Better UX with disabled states for poor quality clusters
 */
@Composable
fun ClusterGridScreen(
    result: ClusteringResult,
    onSelectCluster: (FaceCluster) -> Unit,
    modifier: Modifier = Modifier,
    qualityAnalyzer: ClusterQualityAnalyzer = remember { ClusterQualityAnalyzer() }
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // Header
        Text(
            text = "Found ${result.clusters.size} ${if (result.clusters.size == 1) "Person" else "People"}",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

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

        Text(
            text = "Tap a cluster to name the person",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

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

        // Grid of clusters
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            items(result.clusters) { cluster ->
                // Analyze quality for each cluster
                val qualityResult = remember(cluster) {
                    qualityAnalyzer.analyzeCluster(cluster)
                }

                ClusterCard(
                    cluster = cluster,
                    qualityTier = qualityResult.qualityTier,
                    canTrain = qualityResult.canTrain,
                    onClick = { onSelectCluster(cluster) }
                )
            }
        }
    }
}

/**
 * Single cluster card with 2x2 face grid and quality badge
 */
@Composable
private fun ClusterCard(
    cluster: FaceCluster,
    qualityTier: ClusterQualityTier,
    canTrain: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(1f)
            .clickable(onClick = onClick), // Always clickable - let dialog handle validation
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = when {
                qualityTier == ClusterQualityTier.POOR ->
                    MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.3f)
                !canTrain ->
                    MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
                else ->
                    MaterialTheme.colorScheme.surface
            }
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize()
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                // 2x2 grid of faces
                val facesToShow = cluster.representativeFaces.take(4)

                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    // Top row (2 faces)
                    Row(modifier = Modifier.weight(1f)) {
                        facesToShow.getOrNull(0)?.let { face ->
                            FaceThumbnail(
                                imageUri = face.imageUri,
                                enabled = canTrain,
                                modifier = Modifier.weight(1f)
                            )
                        } ?: EmptyFaceSlot(Modifier.weight(1f))

                        facesToShow.getOrNull(1)?.let { face ->
                            FaceThumbnail(
                                imageUri = face.imageUri,
                                enabled = canTrain,
                                modifier = Modifier.weight(1f)
                            )
                        } ?: EmptyFaceSlot(Modifier.weight(1f))
                    }

                    // Bottom row (2 faces)
                    Row(modifier = Modifier.weight(1f)) {
                        facesToShow.getOrNull(2)?.let { face ->
                            FaceThumbnail(
                                imageUri = face.imageUri,
                                enabled = canTrain,
                                modifier = Modifier.weight(1f)
                            )
                        } ?: EmptyFaceSlot(Modifier.weight(1f))

                        facesToShow.getOrNull(3)?.let { face ->
                            FaceThumbnail(
                                imageUri = face.imageUri,
                                enabled = canTrain,
                                modifier = Modifier.weight(1f)
                            )
                        } ?: EmptyFaceSlot(Modifier.weight(1f))
                    }
                }

                // Footer with photo count
                Surface(
                    modifier = Modifier.fillMaxWidth(),
                    color = if (canTrain) {
                        MaterialTheme.colorScheme.primaryContainer
                    } else {
                        MaterialTheme.colorScheme.surfaceVariant
                    }
                ) {
                    Row(
                        modifier = Modifier.padding(12.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "${cluster.photoCount} photos",
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = FontWeight.SemiBold,
                            color = if (canTrain) {
                                MaterialTheme.colorScheme.onPrimaryContainer
                            } else {
                                MaterialTheme.colorScheme.onSurfaceVariant
                            }
                        )
                    }
                }
            }

            // Quality badge overlay
            QualityBadge(
                qualityTier = qualityTier,
                canTrain = canTrain,
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(8.dp)
            )
        }
    }
}

/**
 * Quality badge indicator
 */
@Composable
private fun QualityBadge(
    qualityTier: ClusterQualityTier,
    canTrain: Boolean,
    modifier: Modifier = Modifier
) {
    val (backgroundColor, iconColor, icon) = when (qualityTier) {
        ClusterQualityTier.EXCELLENT -> Triple(
            Color(0xFF1B5E20),
            Color.White,
            Icons.Default.Check
        )
        ClusterQualityTier.GOOD -> Triple(
            Color(0xFF2E7D32),
            Color.White,
            Icons.Default.Check
        )
        ClusterQualityTier.POOR -> Triple(
            Color(0xFFD32F2F),
            Color.White,
            Icons.Default.Warning
        )
    }

    Surface(
        modifier = modifier,
        shape = CircleShape,
        color = backgroundColor,
        shadowElevation = 2.dp
    ) {
        Box(
            modifier = Modifier
                .size(32.dp)
                .padding(6.dp),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = qualityTier.name,
                tint = iconColor,
                modifier = Modifier.size(20.dp)
            )
        }
    }
}

@Composable
private fun FaceThumbnail(
    imageUri: String,
    enabled: Boolean,
    modifier: Modifier = Modifier
) {
    Box(modifier = modifier) {
        AsyncImage(
            model = Uri.parse(imageUri),
            contentDescription = "Face",
            modifier = Modifier
                .fillMaxSize()
                .border(
                    width = 0.5.dp,
                    color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
                ),
            contentScale = ContentScale.Crop,
            alpha = if (enabled) 1f else 0.6f
        )
    }
}

@Composable
private fun EmptyFaceSlot(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surfaceVariant)
            .border(
                width = 0.5.dp,
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
            )
    )
}