package com.placeholder.sherpai2.ui.imagedetail

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.Color
import androidx.compose.ui.layout.ContentScale
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 androidx.navigation.NavController
import coil.compose.AsyncImage
import com.placeholder.sherpai2.data.local.entity.TagEntity
import com.placeholder.sherpai2.ui.imagedetail.viewmodel.FaceTagInfo
import com.placeholder.sherpai2.ui.imagedetail.viewmodel.ImageDetailViewModel
import net.engawapg.lib.zoomable.rememberZoomState
import net.engawapg.lib.zoomable.zoomable
import java.net.URLEncoder

/**
 * ImageDetailScreen - COMPLETE with navigation and tags
 *
 * Features:
 * - Full-screen zoomable image
 * - Previous/Next navigation buttons
 * - Image counter (3/45)
 * - Tags button (toggle show/hide)
 * - Shows all tags on photo
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageDetailScreen(
    modifier: Modifier = Modifier,
    imageUri: String,
    onBack: () -> Unit,
    navController: NavController? = null,
    allImageUris: List<String> = emptyList(), // Pass from caller
    viewModel: ImageDetailViewModel = hiltViewModel() // ✅ FIXED: Use hiltViewModel
) {

    LaunchedEffect(imageUri) {
        viewModel.loadImage(imageUri)
    }

    val tags by viewModel.tags.collectAsStateWithLifecycle()
    val faceTags by viewModel.faceTags.collectAsStateWithLifecycle()
    var showTags by remember { mutableStateOf(false) }

    // Total tag count for badge
    val totalTagCount = tags.size + faceTags.size

    // Navigation state
    val currentIndex = if (allImageUris.isNotEmpty()) allImageUris.indexOf(imageUri) else -1
    val hasNavigation = allImageUris.isNotEmpty() && currentIndex >= 0
    val canGoPrevious = hasNavigation && currentIndex > 0
    val canGoNext = hasNavigation && currentIndex < allImageUris.size - 1

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    if (hasNavigation) {
                        Text(
                            "${currentIndex + 1} / ${allImageUris.size}",
                            style = MaterialTheme.typography.titleMedium
                        )
                    } else {
                        Text("Photo")
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, "Back")
                    }
                },
                actions = {
                    // Tags toggle button
                    IconButton(onClick = { showTags = !showTags }) {
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(4.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            if (totalTagCount > 0) {
                                Badge(
                                    containerColor = if (showTags)
                                        MaterialTheme.colorScheme.primary
                                    else if (faceTags.isNotEmpty())
                                        MaterialTheme.colorScheme.tertiary
                                    else
                                        MaterialTheme.colorScheme.surfaceVariant
                                ) {
                                    Text(
                                        totalTagCount.toString(),
                                        color = if (showTags)
                                            MaterialTheme.colorScheme.onPrimary
                                        else if (faceTags.isNotEmpty())
                                            MaterialTheme.colorScheme.onTertiary
                                        else
                                            MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                            Icon(
                                if (faceTags.isNotEmpty()) Icons.Default.Face
                                else if (showTags) Icons.Default.Label
                                else Icons.Default.LocalOffer,
                                "Show Tags",
                                tint = if (showTags)
                                    MaterialTheme.colorScheme.primary
                                else if (faceTags.isNotEmpty())
                                    MaterialTheme.colorScheme.tertiary
                                else
                                    MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    // Previous button (only show if has navigation)
                    if (hasNavigation && navController != null) {
                        IconButton(
                            onClick = {
                                if (canGoPrevious) {
                                    val prevUri = allImageUris[currentIndex - 1]
                                    val encoded = URLEncoder.encode(prevUri, "UTF-8")
                                    navController.navigate("image_detail/$encoded") {
                                        popUpTo("image_detail/${URLEncoder.encode(imageUri, "UTF-8")}") {
                                            inclusive = true
                                        }
                                    }
                                }
                            },
                            enabled = canGoPrevious
                        ) {
                            Icon(Icons.Default.KeyboardArrowLeft, "Previous")
                        }

                        // Next button (only show if has navigation)
                        IconButton(
                            onClick = {
                                if (canGoNext) {
                                    val nextUri = allImageUris[currentIndex + 1]
                                    val encoded = URLEncoder.encode(nextUri, "UTF-8")
                                    navController.navigate("image_detail/$encoded") {
                                        popUpTo("image_detail/${URLEncoder.encode(imageUri, "UTF-8")}") {
                                            inclusive = true
                                        }
                                    }
                                }
                            },
                            enabled = canGoNext
                        ) {
                            Icon(Icons.Default.KeyboardArrowRight, "Next")
                        }
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Zoomable image
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .background(Color.Black)
            ) {
                val zoomState = rememberZoomState()

                AsyncImage(
                    model = imageUri,
                    contentDescription = "Photo",
                    modifier = Modifier
                        .fillMaxSize()
                        .zoomable(zoomState),
                    contentScale = ContentScale.Fit
                )
            }

            // Tags panel (slides up when enabled)
            if (showTags) {
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 300.dp),
                    color = MaterialTheme.colorScheme.surfaceVariant,
                    tonalElevation = 3.dp
                ) {
                    LazyColumn(
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // Face Tags Section (People in Photo)
                        if (faceTags.isNotEmpty()) {
                            item {
                                Text(
                                    "People (${faceTags.size})",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold,
                                    color = MaterialTheme.colorScheme.tertiary
                                )
                            }

                            items(faceTags, key = { it.tagId }) { faceTag ->
                                FaceTagCard(
                                    faceTag = faceTag,
                                    onRemove = { viewModel.removeFaceTag(faceTag) }
                                )
                            }

                            item {
                                Spacer(modifier = Modifier.height(8.dp))
                            }
                        }

                        // Regular Tags Section
                        item {
                            Text(
                                "Tags (${tags.size})",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold
                            )
                        }

                        if (tags.isEmpty() && faceTags.isEmpty()) {
                            item {
                                Text(
                                    "No tags yet",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        } else if (tags.isEmpty()) {
                            item {
                                Text(
                                    "No other tags",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }

                        items(tags, key = { it.tagId }) { tag ->
                            TagCard(
                                tag = tag,
                                onRemove = { viewModel.removeTag(tag) }
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun FaceTagCard(
    faceTag: FaceTagInfo,
    onRemove: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.tertiaryContainer
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Default.Face,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.tertiary
                    )
                    Text(
                        text = faceTag.personName,
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.SemiBold
                    )
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "Face Recognition",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "•",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "${(faceTag.confidence * 100).toInt()}% confidence",
                        style = MaterialTheme.typography.labelSmall,
                        color = if (faceTag.confidence >= 0.7f)
                            MaterialTheme.colorScheme.primary
                        else if (faceTag.confidence >= 0.5f)
                            MaterialTheme.colorScheme.secondary
                        else
                            MaterialTheme.colorScheme.error
                    )
                }
            }

            // Remove button
            IconButton(
                onClick = onRemove,
                colors = IconButtonDefaults.iconButtonColors(
                    contentColor = MaterialTheme.colorScheme.error
                )
            ) {
                Icon(Icons.Default.Delete, "Remove face tag")
            }
        }
    }
}

@Composable
private fun TagCard(
    tag: TagEntity,
    onRemove: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = when (tag.type) {
                "PERSON" -> MaterialTheme.colorScheme.primaryContainer
                "SYSTEM" -> MaterialTheme.colorScheme.secondaryContainer
                else -> MaterialTheme.colorScheme.tertiaryContainer
            }
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = when (tag.type) {
                            "PERSON" -> Icons.Default.Face
                            "SYSTEM" -> Icons.Default.AutoAwesome
                            else -> Icons.Default.Label
                        },
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                        tint = when (tag.type) {
                            "PERSON" -> MaterialTheme.colorScheme.primary
                            "SYSTEM" -> MaterialTheme.colorScheme.secondary
                            else -> MaterialTheme.colorScheme.tertiary
                        }
                    )
                    Text(
                        text = tag.getDisplayValue(), // Uses TagEntity's built-in method
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.SemiBold
                    )
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = tag.type.lowercase().replaceFirstChar { it.uppercase() },
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "•",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = formatTimestamp(tag.createdAt),
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            // Remove button (only for user-created tags)
            if (tag.isUserTag()) {
                IconButton(
                    onClick = onRemove,
                    colors = IconButtonDefaults.iconButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Icon(Icons.Default.Delete, "Remove tag")
                }
            }
        }
    }
}

/**
 * Format timestamp to relative time
 */
private fun formatTimestamp(timestamp: Long): String {
    val now = System.currentTimeMillis()
    val diff = now - timestamp

    return when {
        diff < 60_000 -> "Just now"
        diff < 3600_000 -> "${diff / 60_000}m ago"
        diff < 86400_000 -> "${diff / 3600_000}h ago"
        diff < 604800_000 -> "${diff / 86400_000}d ago"
        else -> "${diff / 604800_000}w ago"
    }
}