package com.placeholder.sherpai2.ui.utilities

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
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.vector.ImageVector
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 com.placeholder.sherpai2.ui.utilities.stats.StatsScreen

/**
 * CLEANED PhotoUtilitiesScreen - No duplicate header
 *
 * Removed:
 * - Scaffold wrapper (lines 36-74)
 * - TopAppBar (was creating banner)
 * - "Photo Utilities" title (MainScreen shows it)
 *
 * Features:
 * - Stats tab (photo statistics and analytics)
 * - Tools tab (scan, duplicates, bursts, quality)
 * - Clean TabRow navigation
 */
@Composable
fun PhotoUtilitiesScreen(
    viewModel: PhotoUtilitiesViewModel = hiltViewModel(),
    modifier: Modifier = Modifier
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val scanProgress by viewModel.scanProgress.collectAsStateWithLifecycle()

    var selectedTab by remember { mutableStateOf(0) }

    Column(modifier = modifier.fillMaxSize()) {
        // TabRow for Stats/Tools
        TabRow(
            selectedTabIndex = selectedTab,
            containerColor = MaterialTheme.colorScheme.surface,
            contentColor = MaterialTheme.colorScheme.primary
        ) {
            Tab(
                selected = selectedTab == 0,
                onClick = { selectedTab = 0 },
                text = { Text("Stats") },
                icon = { Icon(Icons.Default.BarChart, "Statistics") }
            )
            Tab(
                selected = selectedTab == 1,
                onClick = { selectedTab = 1 },
                text = { Text("Tools") },
                icon = { Icon(Icons.Default.Build, "Tools") }
            )
        }

        // Tab content
        when (selectedTab) {
            0 -> {
                // Stats tab
                StatsScreen()
            }
            1 -> {
                // Tools tab
                ToolsTabContent(
                    uiState = uiState,
                    scanProgress = scanProgress,
                    onPopulateFaceCache = { viewModel.populateFaceCache() },
                    onForceRebuildCache = { viewModel.forceRebuildFaceCache() },
                    onScanPhotos = { viewModel.scanForPhotos() },
                    onDetectDuplicates = { viewModel.detectDuplicates() },
                    onDetectBursts = { viewModel.detectBursts() },
                    onAnalyzeQuality = { viewModel.analyzeQuality() }
                )
            }
        }
    }
}

@Composable
private fun ToolsTabContent(
    uiState: UtilitiesUiState,
    scanProgress: ScanProgress?,
    onPopulateFaceCache: () -> Unit,
    onForceRebuildCache: () -> Unit,
    onScanPhotos: () -> Unit,
    onDetectDuplicates: () -> Unit,
    onDetectBursts: () -> Unit,
    onAnalyzeQuality: () -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(
        modifier = modifier.fillMaxSize(),
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Section: Face Recognition Cache (MOST IMPORTANT)
        item {
            SectionHeader(
                title = "Face Recognition",
                icon = Icons.Default.Face
            )
        }

        item {
            UtilityCard(
                title = "Populate Face Cache",
                description = "Scan all photos to detect which ones have faces. Required for Discovery to work!",
                icon = Icons.Default.FaceRetouchingNatural,
                buttonText = "Scan for Faces",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = { onPopulateFaceCache() }
            )
        }

        item {
            UtilityCard(
                title = "Force Rebuild Cache",
                description = "Clear and rebuild entire face cache. Use if cache seems corrupted.",
                icon = Icons.Default.Refresh,
                buttonText = "Force Rebuild",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = { onForceRebuildCache() }
            )
        }

        // Section: Scan & Import
        item {
            Spacer(Modifier.height(8.dp))
            SectionHeader(
                title = "Scan & Import",
                icon = Icons.Default.Scanner
            )
        }

        item {
            UtilityCard(
                title = "Scan for Photos",
                description = "Search your device for new photos",
                icon = Icons.Default.PhotoLibrary,
                buttonText = "Scan Now",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = onScanPhotos
            )
        }

        // Section: Organization
        item {
            Spacer(Modifier.height(8.dp))
            SectionHeader(
                title = "Organization",
                icon = Icons.Default.Folder
            )
        }

        item {
            UtilityCard(
                title = "Detect Duplicates",
                description = "Find and tag duplicate photos",
                icon = Icons.Default.FileCopy,
                buttonText = "Find Duplicates",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = onDetectDuplicates
            )
        }

        item {
            UtilityCard(
                title = "Detect Bursts",
                description = "Group photos taken in rapid succession (3+ in 2 seconds)",
                icon = Icons.Default.BurstMode,
                buttonText = "Find Bursts",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = onDetectBursts
            )
        }

        // Section: Quality
        item {
            Spacer(Modifier.height(8.dp))
            SectionHeader(
                title = "Quality Analysis",
                icon = Icons.Default.HighQuality
            )
        }

        item {
            UtilityCard(
                title = "Find Screenshots & Blurry",
                description = "Identify screenshots and low-quality photos",
                icon = Icons.Default.PhoneAndroid,
                buttonText = "Analyze",
                enabled = uiState !is UtilitiesUiState.Scanning,
                onClick = onAnalyzeQuality
            )
        }

        // Progress indicator
        if (scanProgress != null) {
            item {
                ProgressCard(scanProgress)
            }
        }

        // Results
        when (val state = uiState) {
            is UtilitiesUiState.ScanComplete -> {
                item {
                    ResultCard(
                        title = "Scan Complete",
                        message = state.message,
                        icon = Icons.Default.CheckCircle,
                        iconTint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            is UtilitiesUiState.DuplicatesFound -> {
                item {
                    ResultCard(
                        title = "Duplicates Found",
                        message = "Found ${state.groups.size} groups of duplicates (${state.groups.sumOf { it.images.size - 1 }} duplicate photos)",
                        icon = Icons.Default.Info,
                        iconTint = MaterialTheme.colorScheme.tertiary
                    )
                }
            }
            is UtilitiesUiState.BurstsFound -> {
                item {
                    ResultCard(
                        title = "Bursts Found",
                        message = "Found ${state.groups.size} burst sequences (${state.groups.sumOf { it.images.size }} photos total)",
                        icon = Icons.Default.Info,
                        iconTint = MaterialTheme.colorScheme.tertiary
                    )
                }
            }
            is UtilitiesUiState.QualityAnalysisComplete -> {
                item {
                    ResultCard(
                        title = "Analysis Complete",
                        message = "Screenshots: ${state.screenshots}\nBlurry: ${state.blurry}",
                        icon = Icons.Default.CheckCircle,
                        iconTint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            is UtilitiesUiState.Error -> {
                item {
                    ResultCard(
                        title = "Error",
                        message = state.message,
                        icon = Icons.Default.Error,
                        iconTint = MaterialTheme.colorScheme.error
                    )
                }
            }
            else -> {}
        }

        // Info card
        item {
            Spacer(Modifier.height(8.dp))
            InfoCard()
        }
    }
}

@Composable
private fun SectionHeader(
    title: String,
    icon: ImageVector
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier.padding(vertical = 4.dp)
    ) {
        Icon(
            icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(20.dp)
        )
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
    }
}

@Composable
private fun UtilityCard(
    title: String,
    description: String,
    icon: ImageVector,
    buttonText: String,
    enabled: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    modifier = Modifier.size(48.dp),
                    shape = RoundedCornerShape(12.dp),
                    color = MaterialTheme.colorScheme.primaryContainer
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Icon(
                            icon,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onPrimaryContainer,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                }

                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = title,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold
                    )
                    Text(
                        text = description,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            Button(
                onClick = onClick,
                modifier = Modifier.fillMaxWidth(),
                enabled = enabled,
                shape = RoundedCornerShape(12.dp)
            ) {
                Text(buttonText)
            }
        }
    }
}

@Composable
private fun ProgressCard(progress: ScanProgress) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = progress.message,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium
                )
                Text(
                    text = "${progress.current}/${progress.total}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            LinearProgressIndicator(
                progress = { progress.current.toFloat() / progress.total.toFloat() },
                modifier = Modifier.fillMaxWidth(),
            )
        }
    }
}

@Composable
private fun ResultCard(
    title: String,
    message: String,
    icon: ImageVector,
    iconTint: androidx.compose.ui.graphics.Color
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                icon,
                contentDescription = null,
                tint = iconTint,
                modifier = Modifier.size(32.dp)
            )
            Column {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = message,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
private fun InfoCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.3f)
        )
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.Default.Info,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSecondaryContainer,
                modifier = Modifier.size(20.dp)
            )
            Text(
                text = "These tools help you organize and maintain your photo collection",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
        }
    }
}