package com.placeholder.sherpai2.ui.search

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.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.placeholder.sherpai2.data.local.entity.PersonEntity

/**
 * ENHANCED SearchScreen
 *
 * NEW FEATURES:
 * ✅ Face filtering (Has Faces / No Faces)
 * ✅ X button on each filter chip for easy removal
 * ✅ Tap to swap include/exclude (kept)
 * ✅ Better visual hierarchy
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
    modifier: Modifier = Modifier,
    searchViewModel: SearchViewModel,
    onImageClick: (String) -> Unit,
    onAlbumClick: ((String) -> Unit)? = null,
    onSaveToCollection: ((
        includedPeople: Set<String>,
        excludedPeople: Set<String>,
        includedTags: Set<String>,
        excludedTags: Set<String>,
        dateRange: DateRange,
        photoCount: Int
    ) -> Unit)? = null
) {
    val searchQuery by searchViewModel.searchQuery.collectAsStateWithLifecycle()
    val includedPeople by searchViewModel.includedPeople.collectAsStateWithLifecycle()
    val excludedPeople by searchViewModel.excludedPeople.collectAsStateWithLifecycle()
    val includedTags by searchViewModel.includedTags.collectAsStateWithLifecycle()
    val excludedTags by searchViewModel.excludedTags.collectAsStateWithLifecycle()
    val dateRange by searchViewModel.dateRange.collectAsStateWithLifecycle()
    val faceFilter by searchViewModel.faceFilter.collectAsStateWithLifecycle()

    val availablePeople by searchViewModel.availablePeople.collectAsStateWithLifecycle()
    val availableTags by searchViewModel.availableTags.collectAsStateWithLifecycle()

    val images by searchViewModel
        .searchImages()
        .collectAsStateWithLifecycle(initialValue = emptyList())

    var showPeoplePicker by remember { mutableStateOf(false) }
    var showTagPicker by remember { mutableStateOf(false) }
    var showFaceFilterMenu by remember { mutableStateOf(false) }

    Column(modifier = modifier.fillMaxSize()) {
        // Search bar + quick add buttons
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = searchQuery,
                onValueChange = { searchViewModel.setSearchQuery(it) },
                placeholder = { Text("Search tags...") },
                leadingIcon = { Icon(Icons.Default.Search, null) },
                trailingIcon = {
                    if (searchQuery.isNotEmpty()) {
                        IconButton(onClick = { searchViewModel.setSearchQuery("") }) {
                            Icon(Icons.Default.Close, "Clear")
                        }
                    }
                },
                modifier = Modifier.weight(1f),
                singleLine = true,
                shape = RoundedCornerShape(12.dp)
            )

            // Add person button
            IconButton(
                onClick = { showPeoplePicker = true },
                colors = IconButtonDefaults.iconButtonColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                )
            ) {
                Icon(Icons.Default.PersonAdd, "Add person filter")
            }

            // Add tag button
            IconButton(
                onClick = { showTagPicker = true },
                colors = IconButtonDefaults.iconButtonColors(
                    containerColor = MaterialTheme.colorScheme.secondaryContainer
                )
            ) {
                Icon(Icons.Default.LabelImportant, "Add tag filter")
            }

            // Face filter button (NEW!)
            IconButton(
                onClick = { showFaceFilterMenu = true },
                colors = IconButtonDefaults.iconButtonColors(
                    containerColor = if (faceFilter != FaceFilter.ALL) {
                        MaterialTheme.colorScheme.tertiaryContainer
                    } else {
                        MaterialTheme.colorScheme.surfaceVariant
                    }
                )
            ) {
                Icon(
                    when (faceFilter) {
                        FaceFilter.HAS_FACES -> Icons.Default.Face
                        FaceFilter.NO_FACES -> Icons.Default.HideImage
                        else -> Icons.Default.FilterAlt
                    },
                    "Face filter"
                )
            }
        }

        // Active filters display (chips)
        if (searchViewModel.hasActiveFilters()) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 4.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
                )
            ) {
                Column(
                    modifier = Modifier.padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            "Active Filters",
                            style = MaterialTheme.typography.labelLarge,
                            fontWeight = FontWeight.Bold
                        )
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            // Save to Collection button
                            if (onSaveToCollection != null && images.isNotEmpty()) {
                                FilledTonalButton(
                                    onClick = {
                                        onSaveToCollection(
                                            includedPeople,
                                            excludedPeople,
                                            includedTags,
                                            excludedTags,
                                            dateRange,
                                            images.size
                                        )
                                    },
                                    contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)
                                ) {
                                    Icon(
                                        Icons.Default.Collections,
                                        contentDescription = null,
                                        modifier = Modifier.size(16.dp)
                                    )
                                    Spacer(Modifier.width(4.dp))
                                    Text("Save", style = MaterialTheme.typography.labelMedium)
                                }
                            }
                            TextButton(
                                onClick = { searchViewModel.clearAllFilters() },
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
                            ) {
                                Text("Clear All", style = MaterialTheme.typography.labelMedium)
                            }
                        }
                    }

                    // Face Filter Chip (NEW!)
                    if (faceFilter != FaceFilter.ALL) {
                        FilterChipWithX(
                            label = faceFilter.displayName,
                            color = MaterialTheme.colorScheme.tertiaryContainer,
                            onTap = { showFaceFilterMenu = true },
                            onRemove = { searchViewModel.setFaceFilter(FaceFilter.ALL) },
                            leadingIcon = {
                                Icon(
                                    when (faceFilter) {
                                        FaceFilter.HAS_FACES -> Icons.Default.Face
                                        FaceFilter.NO_FACES -> Icons.Default.HideImage
                                        else -> Icons.Default.FilterAlt
                                    },
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp)
                                )
                            }
                        )
                    }

                    // Included People (GREEN)
                    if (includedPeople.isNotEmpty()) {
                        LazyRow(
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                            contentPadding = PaddingValues(vertical = 4.dp)
                        ) {
                            items(includedPeople.toList()) { personId ->
                                val person = availablePeople.find { it.id == personId }
                                if (person != null) {
                                    FilterChipWithX(
                                        label = person.name,
                                        color = Color(0xFF4CAF50).copy(alpha = 0.3f),
                                        onTap = { searchViewModel.excludePerson(personId) },
                                        onRemove = { searchViewModel.removePersonFilter(personId) },
                                        leadingIcon = {
                                            Icon(
                                                Icons.Default.Person,
                                                contentDescription = null,
                                                modifier = Modifier.size(16.dp),
                                                tint = Color(0xFF2E7D32)
                                            )
                                        }
                                    )
                                }
                            }
                        }
                    }

                    // Excluded People (RED)
                    if (excludedPeople.isNotEmpty()) {
                        LazyRow(
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                            contentPadding = PaddingValues(vertical = 4.dp)
                        ) {
                            items(excludedPeople.toList()) { personId ->
                                val person = availablePeople.find { it.id == personId }
                                if (person != null) {
                                    FilterChipWithX(
                                        label = person.name,
                                        color = Color(0xFFF44336).copy(alpha = 0.3f),
                                        onTap = { searchViewModel.includePerson(personId) },
                                        onRemove = { searchViewModel.removePersonFilter(personId) },
                                        leadingIcon = {
                                            Icon(
                                                Icons.Default.PersonOff,
                                                contentDescription = null,
                                                modifier = Modifier.size(16.dp),
                                                tint = Color(0xFFC62828)
                                            )
                                        }
                                    )
                                }
                            }
                        }
                    }

                    // Included Tags (GREEN)
                    if (includedTags.isNotEmpty()) {
                        LazyRow(
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                            contentPadding = PaddingValues(vertical = 4.dp)
                        ) {
                            items(includedTags.toList()) { tag ->
                                FilterChipWithX(
                                    label = tag,
                                    color = Color(0xFF4CAF50).copy(alpha = 0.3f),
                                    onTap = { searchViewModel.excludeTag(tag) },
                                    onRemove = { searchViewModel.removeTagFilter(tag) },
                                    leadingIcon = {
                                        Icon(
                                            Icons.Default.Label,
                                            contentDescription = null,
                                            modifier = Modifier.size(16.dp),
                                            tint = Color(0xFF2E7D32)
                                        )
                                    }
                                )
                            }
                        }
                    }

                    // Excluded Tags (RED)
                    if (excludedTags.isNotEmpty()) {
                        LazyRow(
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                            contentPadding = PaddingValues(vertical = 4.dp)
                        ) {
                            items(excludedTags.toList()) { tag ->
                                FilterChipWithX(
                                    label = tag,
                                    color = Color(0xFFF44336).copy(alpha = 0.3f),
                                    onTap = { searchViewModel.includeTag(tag) },
                                    onRemove = { searchViewModel.removeTagFilter(tag) },
                                    leadingIcon = {
                                        Icon(
                                            Icons.Default.LabelOff,
                                            contentDescription = null,
                                            modifier = Modifier.size(16.dp),
                                            tint = Color(0xFFC62828)
                                        )
                                    }
                                )
                            }
                        }
                    }
                }
            }
        }

        // Results
        when {
            images.isEmpty() && searchViewModel.hasActiveFilters() -> NoResultsState()
            images.isEmpty() && !searchViewModel.hasActiveFilters() -> EmptyState()
            else -> {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 120.dp),
                    contentPadding = PaddingValues(16.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    items(images.size) { index ->
                        val imageWithTags = images[index]
                        Card(
                            modifier = Modifier
                                .aspectRatio(1f)
                                .clickable { onImageClick(imageWithTags.image.imageUri) },
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            AsyncImage(
                                model = imageWithTags.image.imageUri,
                                contentDescription = null,
                                modifier = Modifier.fillMaxSize()
                            )
                        }
                    }
                }
            }
        }
    }

    // Face filter menu
    if (showFaceFilterMenu) {
        FaceFilterMenu(
            currentFilter = faceFilter,
            onSelect = { filter ->
                searchViewModel.setFaceFilter(filter)
                showFaceFilterMenu = false
            },
            onDismiss = { showFaceFilterMenu = false }
        )
    }

    // People picker dialog
    if (showPeoplePicker) {
        PeoplePickerDialog(
            people = availablePeople,
            includedPeople = includedPeople,
            excludedPeople = excludedPeople,
            onInclude = { searchViewModel.includePerson(it) },
            onExclude = { searchViewModel.excludePerson(it) },
            onDismiss = { showPeoplePicker = false }
        )
    }

    // Tag picker dialog
    if (showTagPicker) {
        TagPickerDialog(
            tags = availableTags,
            includedTags = includedTags,
            excludedTags = excludedTags,
            onInclude = { searchViewModel.includeTag(it) },
            onExclude = { searchViewModel.excludeTag(it) },
            onDismiss = { showTagPicker = false }
        )
    }
}

/**
 * NEW: Filter chip with X button for easy removal
 */
@Composable
private fun FilterChipWithX(
    label: String,
    color: Color,
    onTap: () -> Unit,
    onRemove: () -> Unit,
    leadingIcon: @Composable (() -> Unit)? = null
) {
    Surface(
        color = color,
        shape = RoundedCornerShape(16.dp),
        modifier = Modifier.height(32.dp)
    ) {
        Row(
            modifier = Modifier.padding(start = 8.dp, end = 4.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            if (leadingIcon != null) {
                leadingIcon()
            }

            Text(
                text = label,
                style = MaterialTheme.typography.labelMedium,
                fontWeight = FontWeight.SemiBold,
                modifier = Modifier.clickable(onClick = onTap)
            )

            IconButton(
                onClick = onRemove,
                modifier = Modifier.size(24.dp)
            ) {
                Icon(
                    Icons.Default.Close,
                    contentDescription = "Remove",
                    modifier = Modifier.size(16.dp)
                )
            }
        }
    }
}

/**
 * NEW: Face filter menu
 */
@Composable
private fun FaceFilterMenu(
    currentFilter: FaceFilter,
    onSelect: (FaceFilter) -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Filter by Faces") },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                FaceFilter.values().forEach { filter ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onSelect(filter) },
                        colors = CardDefaults.cardColors(
                            containerColor = if (filter == currentFilter) {
                                MaterialTheme.colorScheme.primaryContainer
                            } else {
                                MaterialTheme.colorScheme.surfaceVariant
                            }
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            horizontalArrangement = Arrangement.spacedBy(12.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                when (filter) {
                                    FaceFilter.ALL -> Icons.Default.FilterAlt
                                    FaceFilter.HAS_FACES -> Icons.Default.Face
                                    FaceFilter.NO_FACES -> Icons.Default.HideImage
                                },
                                contentDescription = null
                            )
                            Column {
                                Text(
                                    filter.displayName,
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold
                                )
                                Text(
                                    when (filter) {
                                        FaceFilter.ALL -> "Show all photos"
                                        FaceFilter.HAS_FACES -> "Only photos with detected faces"
                                        FaceFilter.NO_FACES -> "Only photos without faces"
                                    },
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Done")
            }
        }
    )
}

// ... Rest of dialogs remain the same ...
@Composable
private fun PeoplePickerDialog(
    people: List<PersonEntity>,
    includedPeople: Set<String>,
    excludedPeople: Set<String>,
    onInclude: (String) -> Unit,
    onExclude: (String) -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Add Person Filter") },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    "Tap to INCLUDE (green) • Long press to EXCLUDE (red)",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                people.forEach { person ->
                    val isIncluded = person.id in includedPeople
                    val isExcluded = person.id in excludedPeople

                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onInclude(person.id) },
                        colors = CardDefaults.cardColors(
                            containerColor = when {
                                isIncluded -> Color(0xFF4CAF50).copy(alpha = 0.3f)
                                isExcluded -> Color(0xFFF44336).copy(alpha = 0.3f)
                                else -> MaterialTheme.colorScheme.surfaceVariant
                            }
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(12.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(person.name, fontWeight = FontWeight.Medium)
                            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                                IconButton(
                                    onClick = { onInclude(person.id) },
                                    colors = IconButtonDefaults.iconButtonColors(
                                        containerColor = if (isIncluded) Color(0xFF4CAF50) else Color.Transparent
                                    )
                                ) {
                                    Icon(Icons.Default.Check, "Include", tint = if (isIncluded) Color.White else MaterialTheme.colorScheme.onSurface)
                                }
                                IconButton(
                                    onClick = { onExclude(person.id) },
                                    colors = IconButtonDefaults.iconButtonColors(
                                        containerColor = if (isExcluded) Color(0xFFF44336) else Color.Transparent
                                    )
                                ) {
                                    Icon(Icons.Default.Close, "Exclude", tint = if (isExcluded) Color.White else MaterialTheme.colorScheme.onSurface)
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Done")
            }
        }
    )
}

@Composable
private fun TagPickerDialog(
    tags: List<String>,
    includedTags: Set<String>,
    excludedTags: Set<String>,
    onInclude: (String) -> Unit,
    onExclude: (String) -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Add Tag Filter") },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    "Tap to INCLUDE (green) • Long press to EXCLUDE (red)",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                tags.forEach { tagValue ->
                    val isIncluded = tagValue in includedTags
                    val isExcluded = tagValue in excludedTags

                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onInclude(tagValue) },
                        colors = CardDefaults.cardColors(
                            containerColor = when {
                                isIncluded -> Color(0xFF4CAF50).copy(alpha = 0.3f)
                                isExcluded -> Color(0xFFF44336).copy(alpha = 0.3f)
                                else -> MaterialTheme.colorScheme.surfaceVariant
                            }
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(12.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(tagValue, fontWeight = FontWeight.Medium)
                            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                                IconButton(
                                    onClick = { onInclude(tagValue) },
                                    colors = IconButtonDefaults.iconButtonColors(
                                        containerColor = if (isIncluded) Color(0xFF4CAF50) else Color.Transparent
                                    )
                                ) {
                                    Icon(Icons.Default.Check, "Include", tint = if (isIncluded) Color.White else MaterialTheme.colorScheme.onSurface)
                                }
                                IconButton(
                                    onClick = { onExclude(tagValue) },
                                    colors = IconButtonDefaults.iconButtonColors(
                                        containerColor = if (isExcluded) Color(0xFFF44336) else Color.Transparent
                                    )
                                ) {
                                    Icon(Icons.Default.Close, "Exclude", tint = if (isExcluded) Color.White else MaterialTheme.colorScheme.onSurface)
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Done")
            }
        }
    )
}

@Composable
private fun EmptyState() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                Icons.Default.Search,
                contentDescription = null,
                modifier = Modifier.size(64.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
            )
            Text(
                "Advanced Search",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
            Text(
                "Add people, tags, or face filters to search",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun NoResultsState() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Icon(
                Icons.Default.SearchOff,
                contentDescription = null,
                modifier = Modifier.size(64.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
            )
            Text(
                "No photos found",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
            Text(
                "Try different filters",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}