package com.placeholder.sherpai2.ui.tags

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.Brush
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.placeholder.sherpai2.data.local.entity.TagWithUsage

/**
 * CLEANED TagManagementScreen - No Scaffold wrapper
 *
 * Removed:
 * - Scaffold wrapper (line 38)
 * - Moved FAB inline as part of content
 *
 * Features:
 * - Tag list with usage counts
 * - Search functionality
 * - Scanning progress
 * - Delete tags
 * - System/User tag distinction
 */
@Composable
fun TagManagementScreen(
    viewModel: TagManagementViewModel = hiltViewModel(),
    modifier: Modifier = Modifier
) {
    val uiState by viewModel.uiState.collectAsState()
    val scanningState by viewModel.scanningState.collectAsState()

    var showAddTagDialog by remember { mutableStateOf(false) }
    var showScanMenu by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }

    Box(modifier = modifier.fillMaxSize()) {
        Column(modifier = Modifier.fillMaxSize()) {
            // Stats Bar
            StatsBar(uiState)

            // Search Bar
            SearchBar(
                searchQuery = searchQuery,
                onSearchChange = {
                    searchQuery = it
                    viewModel.searchTags(it)
                }
            )

            // Scanning Progress
            AnimatedVisibility(
                visible = scanningState !is TagManagementViewModel.TagScanningState.Idle,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                ScanningProgress(scanningState, viewModel)
            }

            // Tag List
            when (val state = uiState) {
                is TagManagementViewModel.TagUiState.Loading -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
                is TagManagementViewModel.TagUiState.Success -> {
                    if (state.tags.isEmpty()) {
                        EmptyTagsView()
                    } else {
                        TagList(
                            tags = state.tags,
                            onDeleteTag = { viewModel.deleteTag(it) }
                        )
                    }
                }
                is TagManagementViewModel.TagUiState.Error -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Icon(
                                Icons.Default.Error,
                                contentDescription = null,
                                modifier = Modifier.size(48.dp),
                                tint = MaterialTheme.colorScheme.error
                            )
                            Text(
                                text = state.message,
                                color = MaterialTheme.colorScheme.error
                            )
                        }
                    }
                }
            }
        }

        // FAB (inline, positioned over content)
        ScanFAB(
            showMenu = showScanMenu,
            onToggleMenu = { showScanMenu = !showScanMenu },
            onScanAll = {
                viewModel.scanForAllTags()
                showScanMenu = false
            },
            onScanBase = {
                viewModel.scanForBaseTags()
                showScanMenu = false
            },
            onScanRelationships = {
                viewModel.scanForRelationshipTags()
                showScanMenu = false
            },
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(16.dp)
        )
    }

    // Add Tag Dialog
    if (showAddTagDialog) {
        AddTagDialog(
            onDismiss = { showAddTagDialog = false },
            onConfirm = { tagName ->
                viewModel.createUserTag(tagName)
                showAddTagDialog = false
            }
        )
    }
}

/**
 * Stats bar at top
 */
@Composable
private fun StatsBar(uiState: TagManagementViewModel.TagUiState) {
    val (totalTags, totalPhotos) = when (uiState) {
        is TagManagementViewModel.TagUiState.Success -> {
            val photoCount: Int = uiState.tags.sumOf { it.usageCount }
            uiState.tags.size to photoCount
        }
        else -> 0 to 0
    }

    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            StatItem(
                icon = Icons.Default.Label,
                value = totalTags.toString(),
                label = "Tags"
            )
            VerticalDivider(
                modifier = Modifier.height(48.dp),
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
            )
            StatItem(
                icon = Icons.Default.Photo,
                value = totalPhotos.toString(),
                label = "Tagged Photos"
            )
        }
    }
}

@Composable
private fun StatItem(icon: ImageVector, value: String, label: String) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Icon(
            icon,
            contentDescription = null,
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Text(
            value,
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold
        )
        Text(
            label,
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * Search bar
 */
@Composable
private fun SearchBar(
    searchQuery: String,
    onSearchChange: (String) -> Unit
) {
    OutlinedTextField(
        value = searchQuery,
        onValueChange = onSearchChange,
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        placeholder = { Text("Search tags...") },
        leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
        trailingIcon = {
            if (searchQuery.isNotEmpty()) {
                IconButton(onClick = { onSearchChange("") }) {
                    Icon(Icons.Default.Clear, "Clear")
                }
            }
        },
        singleLine = true,
        shape = RoundedCornerShape(16.dp)
    )
}

/**
 * Scanning progress indicator
 */
@Composable
private fun ScanningProgress(
    scanningState: TagManagementViewModel.TagScanningState,
    viewModel: TagManagementViewModel
) {
    when (scanningState) {
        is TagManagementViewModel.TagScanningState.Scanning -> {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f)
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            "Scanning: ${scanningState.scanType}",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.SemiBold
                        )
                        Text(
                            "${scanningState.progress}/${scanningState.total}",
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                    LinearProgressIndicator(
                        progress = {
                            if (scanningState.total > 0) {
                                scanningState.progress.toFloat() / scanningState.total.toFloat()
                            } else {
                                0f
                            }
                        },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Text(
                        "Tags applied: ${scanningState.tagsApplied}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                    if (scanningState.currentImage.isNotEmpty()) {
                        Text(
                            "Current: ${scanningState.currentImage}",
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
        is TagManagementViewModel.TagScanningState.Complete -> {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                )
            ) {
                Row(
                    modifier = Modifier.padding(16.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.CheckCircle,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Column {
                        Text(
                            "Scan Complete!",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            "Processed: ${scanningState.imagesProcessed} images",
                            style = MaterialTheme.typography.bodySmall
                        )
                        Text(
                            "Applied: ${scanningState.tagsApplied} tags",
                            style = MaterialTheme.typography.bodySmall
                        )
                        if (scanningState.newTagsCreated > 0) {
                            Text(
                                "Created: ${scanningState.newTagsCreated} new tags",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                }
            }
        }
        else -> {}
    }
}

/**
 * Tag list
 */
@Composable
private fun TagList(
    tags: List<TagWithUsage>,
    onDeleteTag: (String) -> Unit
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(tags) { tagWithUsage ->
            TagCard(
                tagWithUsage = tagWithUsage,
                onDelete = { onDeleteTag(tagWithUsage.tagId) }
            )
        }
    }
}

/**
 * Individual tag card
 */
@Composable
private fun TagCard(
    tagWithUsage: TagWithUsage,
    onDelete: () -> Unit
) {
    val isSystemTag = tagWithUsage.type == "SYSTEM"

    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                modifier = Modifier.weight(1f),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Tag icon
                Surface(
                    modifier = Modifier.size(40.dp),
                    shape = RoundedCornerShape(8.dp),
                    color = if (isSystemTag)
                        MaterialTheme.colorScheme.primaryContainer
                    else
                        MaterialTheme.colorScheme.secondaryContainer
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Icon(
                            if (isSystemTag) Icons.Default.AutoAwesome else Icons.Default.Label,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                            tint = if (isSystemTag)
                                MaterialTheme.colorScheme.onPrimaryContainer
                            else
                                MaterialTheme.colorScheme.onSecondaryContainer
                        )
                    }
                }

                // Tag info
                Column {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = tagWithUsage.value,
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                        if (isSystemTag) {
                            Surface(
                                shape = RoundedCornerShape(4.dp),
                                color = MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)
                            ) {
                                Text(
                                    "SYSTEM",
                                    modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }
                    Text(
                        text = "${tagWithUsage.usageCount} ${if (tagWithUsage.usageCount == 1) "photo" else "photos"}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            // Delete button (only for user tags)
            if (!isSystemTag) {
                IconButton(onClick = onDelete) {
                    Icon(
                        Icons.Default.Delete,
                        contentDescription = "Delete",
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
        }
    }
}

/**
 * Empty state
 */
@Composable
private fun EmptyTagsView() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                Icons.Default.LabelOff,
                contentDescription = null,
                modifier = Modifier.size(64.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
            )
            Text(
                "No Tags Yet",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
            Text(
                "Scan your photos to generate tags automatically",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = androidx.compose.ui.text.style.TextAlign.Center
            )
        }
    }
}

/**
 * Floating Action Button with scan menu
 */
@Composable
private fun ScanFAB(
    showMenu: Boolean,
    onToggleMenu: () -> Unit,
    onScanAll: () -> Unit,
    onScanBase: () -> Unit,
    onScanRelationships: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Menu options
        AnimatedVisibility(visible = showMenu) {
            Column(
                horizontalAlignment = Alignment.End,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                SmallFAB(
                    icon = Icons.Default.AutoFixHigh,
                    text = "Scan All",
                    onClick = onScanAll
                )
                SmallFAB(
                    icon = Icons.Default.PhotoCamera,
                    text = "Base Tags",
                    onClick = onScanBase
                )
                SmallFAB(
                    icon = Icons.Default.People,
                    text = "Relationships",
                    onClick = onScanRelationships
                )
            }
        }

        // Main FAB
        ExtendedFloatingActionButton(
            onClick = onToggleMenu,
            icon = {
                Icon(
                    if (showMenu) Icons.Default.Close else Icons.Default.AutoFixHigh,
                    "Scan"
                )
            },
            text = { Text(if (showMenu) "Close" else "Scan Tags") },
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            contentColor = MaterialTheme.colorScheme.onPrimaryContainer
        )
    }
}

@Composable
private fun SmallFAB(
    icon: ImageVector,
    text: String,
    onClick: () -> Unit
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Surface(
            shape = RoundedCornerShape(8.dp),
            color = MaterialTheme.colorScheme.surface,
            shadowElevation = 2.dp
        ) {
            Text(
                text,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
                style = MaterialTheme.typography.bodySmall,
                fontWeight = FontWeight.Medium
            )
        }

        FloatingActionButton(
            onClick = onClick,
            modifier = Modifier.size(48.dp),
            containerColor = MaterialTheme.colorScheme.secondaryContainer,
            contentColor = MaterialTheme.colorScheme.onSecondaryContainer
        ) {
            Icon(icon, contentDescription = text, modifier = Modifier.size(20.dp))
        }
    }
}

/**
 * Add tag dialog
 */
@Composable
private fun AddTagDialog(
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit
) {
    var tagName by remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = onDismiss,
        icon = { Icon(Icons.Default.Add, contentDescription = null) },
        title = { Text("Add Custom Tag") },
        text = {
            OutlinedTextField(
                value = tagName,
                onValueChange = { tagName = it },
                label = { Text("Tag Name") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )
        },
        confirmButton = {
            Button(
                onClick = { onConfirm(tagName) },
                enabled = tagName.isNotBlank()
            ) {
                Text("Add")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}