package com.placeholder.sherpai2.ui.album

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.*
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.placeholder.sherpai2.ui.search.DateRange

/**
 * AlbumViewScreen - CLEAN VERSION with Export
 *
 * REMOVED:
 * - DisplayMode toggle
 * - Verbose person tags
 *
 * ADDED:
 * - Export menu (Folder, Zip, Collage)
 * - Clean simple layout
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlbumViewScreen(
    onBack: () -> Unit,
    onImageClick: (String) -> Unit,
    viewModel: AlbumViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
    val dateRange by viewModel.dateRange.collectAsStateWithLifecycle()

    var showExportMenu by remember { mutableStateOf(false) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Column {
                        when (val state = uiState) {
                            is AlbumUiState.Success -> {
                                Text(
                                    text = state.albumName,
                                    style = MaterialTheme.typography.titleLarge,
                                    fontWeight = FontWeight.Bold
                                )
                                Text(
                                    text = "${state.photos.size} photos",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            else -> {
                                Text("Album")
                            }
                        }
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, "Back")
                    }
                },
                actions = {
                    // Export button
                    IconButton(onClick = { showExportMenu = true }) {
                        Icon(Icons.Default.FileDownload, "Export")
                    }
                }
            )
        }
    ) { paddingValues ->
        when (val state = uiState) {
            is AlbumUiState.Loading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }
            is AlbumUiState.Error -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    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(state.message)
                        Button(onClick = onBack) {
                            Text("Go Back")
                        }
                    }
                }
            }
            is AlbumUiState.Success -> {
                AlbumContent(
                    state = state,
                    searchQuery = searchQuery,
                    dateRange = dateRange,
                    onSearchChange = { viewModel.setSearchQuery(it) },
                    onDateRangeChange = { viewModel.setDateRange(it) },
                    onImageClick = onImageClick,
                    modifier = Modifier.padding(paddingValues)
                )
            }
        }
    }

    // Export menu dialog
    if (showExportMenu) {
        ExportDialog(
            albumName = when (val state = uiState) {
                is AlbumUiState.Success -> state.albumName
                else -> "Album"
            },
            photoCount = when (val state = uiState) {
                is AlbumUiState.Success -> state.photos.size
                else -> 0
            },
            onDismiss = { showExportMenu = false },
            onExportToFolder = {
                // TODO: Implement folder export
                showExportMenu = false
            },
            onExportToZip = {
                // TODO: Implement zip export
                showExportMenu = false
            },
            onExportToCollage = {
                // TODO: Implement collage export
                showExportMenu = false
            }
        )
    }
}

@Composable
private fun AlbumContent(
    state: AlbumUiState.Success,
    searchQuery: String,
    dateRange: DateRange,
    onSearchChange: (String) -> Unit,
    onDateRangeChange: (DateRange) -> Unit,
    onImageClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // Stats card
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
            )
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceAround
            ) {
                StatItem(Icons.Default.Photo, "Photos", state.photos.size.toString())
                if (state.totalFaces > 0) {
                    StatItem(Icons.Default.Face, "Faces", state.totalFaces.toString())
                }
                if (state.personCount > 0) {
                    StatItem(Icons.Default.People, "People", state.personCount.toString())
                }
            }
        }

        // Search bar
        OutlinedTextField(
            value = searchQuery,
            onValueChange = onSearchChange,
            placeholder = { Text("Search in album...") },
            leadingIcon = { Icon(Icons.Default.Search, null) },
            trailingIcon = {
                if (searchQuery.isNotEmpty()) {
                    IconButton(onClick = { onSearchChange("") }) {
                        Icon(Icons.Default.Clear, "Clear")
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp),
            singleLine = true,
            shape = RoundedCornerShape(16.dp)
        )

        Spacer(Modifier.height(8.dp))

        // Date filters
        LazyRow(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(DateRange.entries.size) { index ->
                val range = DateRange.entries[index]
                val isActive = dateRange == range
                FilterChip(
                    selected = isActive,
                    onClick = { onDateRangeChange(range) },
                    label = { Text(range.displayName) }
                )
            }
        }

        Spacer(Modifier.height(8.dp))

        // Photo grid
        if (state.photos.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "No photos in this album",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        } else {
            LazyVerticalGrid(
                columns = GridCells.Adaptive(120.dp),
                contentPadding = PaddingValues(12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                modifier = Modifier.fillMaxSize()
            ) {
                items(
                    items = state.photos,
                    key = { it.image.imageId }
                ) { photo ->
                    PhotoCard(
                        photo = photo,
                        onImageClick = onImageClick
                    )
                }
            }
        }
    }
}

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

/**
 * PhotoCard - CLEAN VERSION: Simple image + person names
 */
@Composable
private fun PhotoCard(
    photo: AlbumPhoto,
    onImageClick: (String) -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(1f)
            .clickable { onImageClick(photo.image.imageUri) },
        shape = RoundedCornerShape(12.dp)
    ) {
        Box {
            // Image
            AsyncImage(
                model = photo.image.imageUri,
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = androidx.compose.ui.layout.ContentScale.Crop
            )

            // Person names overlay (if any)
            if (photo.persons.isNotEmpty()) {
                Surface(
                    color = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f),
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .fillMaxWidth()
                ) {
                    Text(
                        text = photo.persons.take(2).joinToString(", ") { it.name },
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.padding(8.dp),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }
    }
}

/**
 * Export Dialog
 */
@Composable
private fun ExportDialog(
    albumName: String,
    photoCount: Int,
    onDismiss: () -> Unit,
    onExportToFolder: () -> Unit,
    onExportToZip: () -> Unit,
    onExportToCollage: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        icon = { Icon(Icons.Default.FileDownload, null) },
        title = { Text("Export Album") },
        text = {
            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Text(
                    "$photoCount photos from \"$albumName\"",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                // Export to Folder
                ExportOption(
                    icon = Icons.Default.Folder,
                    title = "Export to Folder",
                    description = "Save all photos to a folder",
                    onClick = onExportToFolder
                )

                // Export to Zip
                ExportOption(
                    icon = Icons.Default.FolderZip,
                    title = "Export as ZIP",
                    description = "Create a compressed archive",
                    onClick = onExportToZip
                )

                // Export to Collage (placeholder)
                ExportOption(
                    icon = Icons.Default.GridView,
                    title = "Create Collage",
                    description = "Coming soon!",
                    onClick = onExportToCollage,
                    enabled = false
                )
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}

@Composable
private fun ExportOption(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    description: String,
    onClick: () -> Unit,
    enabled: Boolean = true
) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(enabled = enabled, onClick = onClick),
        shape = RoundedCornerShape(12.dp),
        color = if (enabled) {
            MaterialTheme.colorScheme.surfaceVariant
        } else {
            MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        }
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Surface(
                shape = RoundedCornerShape(8.dp),
                color = MaterialTheme.colorScheme.primary.copy(
                    alpha = if (enabled) 1f else 0.5f
                ),
                modifier = Modifier.size(40.dp)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        icon,
                        contentDescription = null,
                        modifier = Modifier.size(24.dp),
                        tint = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }

            Column(modifier = Modifier.weight(1f)) {
                Text(
                    title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = if (enabled) {
                        MaterialTheme.colorScheme.onSurface
                    } else {
                        MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
                    }
                )
                Text(
                    description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(
                        alpha = if (enabled) 1f else 0.5f
                    )
                )
            }

            if (enabled) {
                Icon(
                    Icons.Default.ChevronRight,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}