package de.krisenvorrat.app.ui.item

import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ItemListScreen(
    onAddItem: () -> Unit,
    onItemClick: (String) -> Unit,
    onCategoriesClick: () -> Unit,
    onLocationsClick: () -> Unit,
    onCameraClick: () -> Unit = {},
    viewModel: ItemListViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    var isMenuExpanded by remember { mutableStateOf(false) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Artikel") },
                actions = {
                    if (de.krisenvorrat.app.BuildConfig.FEATURE_CAMERA_ENABLED) {
                        IconButton(onClick = onCameraClick) {
                            Icon(
                                imageVector = Icons.Default.PhotoCamera,
                                contentDescription = "Foto erfassen"
                            )
                        }
                    }
                    IconButton(onClick = { isMenuExpanded = true }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "Menü"
                        )
                    }
                    DropdownMenu(
                        expanded = isMenuExpanded,
                        onDismissRequest = { isMenuExpanded = false }
                    ) {
                        DropdownMenuItem(
                            text = { Text("Kategorien") },
                            onClick = {
                                isMenuExpanded = false
                                onCategoriesClick()
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("Lagerorte") },
                            onClick = {
                                isMenuExpanded = false
                                onLocationsClick()
                            }
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = onAddItem) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "Artikel hinzufügen"
                )
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            ItemSearchBar(
                query = uiState.searchQuery,
                onQueryChanged = viewModel::onSearchQueryChanged,
                onClearClick = viewModel::clearSearch
            )

            FilterChipRow(
                uiState = uiState,
                onCategorySelected = viewModel::onCategoryFilterChanged,
                onLocationSelected = viewModel::onLocationFilterChanged,
                onExpirySelected = viewModel::onExpiryFilterChanged
            )

            when {
                uiState.isEmpty -> EmptyState(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                )
                uiState.hasNoFilterResults -> NoFilterResultsState(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                )
                else -> ItemList(
                    groupedItems = uiState.groupedItems,
                    onItemClick = onItemClick,
                    onDeleteClick = viewModel::showDeleteDialog,
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                )
            }
        }
    }

    if (uiState.isDeleteDialogVisible && uiState.itemToDelete != null) {
        DeleteItemDialog(
            itemName = uiState.itemToDelete?.name.orEmpty(),
            onConfirm = viewModel::deleteItem,
            onDismiss = viewModel::dismissDeleteDialog
        )
    }
}

@Composable
private fun EmptyState(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(
                text = "Noch keine Artikel vorhanden",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "Tippen Sie auf +, um einen Artikel hinzuzufügen",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun ItemList(
    groupedItems: Map<String, List<ItemUiModel>>,
    onItemClick: (String) -> Unit,
    onDeleteClick: (ItemUiModel) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        groupedItems.forEach { (categoryName, items) ->
            item(key = "header_$categoryName") {
                CategoryHeader(categoryName = categoryName)
            }
            items(items, key = { it.id }) { item ->
                ItemCard(
                    item = item,
                    onClick = { onItemClick(item.id) },
                    onDeleteClick = { onDeleteClick(item) }
                )
            }
        }
    }
}

@Composable
private fun CategoryHeader(categoryName: String) {
    Text(
        text = categoryName,
        style = MaterialTheme.typography.titleMedium,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
    )
}

@Composable
private fun ItemCard(
    item: ItemUiModel,
    onClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 2.dp)
            .clickable(onClick = onClick)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = item.name,
                    style = MaterialTheme.typography.bodyLarge
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "${item.quantity} ${item.unit} · ${item.locationName}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                if (item.expiryDate != null) {
                    Spacer(modifier = Modifier.height(2.dp))
                    ExpiryDateText(item = item)
                }
            }
            IconButton(onClick = onDeleteClick) {
                Icon(
                    imageVector = Icons.Default.Delete,
                    contentDescription = "Artikel löschen",
                    tint = MaterialTheme.colorScheme.error
                )
            }
        }
    }
}

@Composable
private fun ExpiryDateText(item: ItemUiModel) {
    val formatter = remember { DateTimeFormatter.ofPattern("MM/yyyy") }
    val formattedDate = item.expiryDate?.format(formatter).orEmpty()
    val color = when {
        item.isExpired -> MaterialTheme.colorScheme.error
        item.isExpiringSoon -> MaterialTheme.colorScheme.tertiary
        else -> MaterialTheme.colorScheme.onSurfaceVariant
    }
    val prefix = if (item.isExpired) "Abgelaufen: " else "MHD: "
    Text(
        text = "$prefix$formattedDate",
        style = MaterialTheme.typography.bodySmall,
        color = color
    )
}

@Composable
private fun ItemSearchBar(
    query: String,
    onQueryChanged: (String) -> Unit,
    onClearClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedTextField(
        value = query,
        onValueChange = onQueryChanged,
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        placeholder = { Text("Suchen...") },
        leadingIcon = {
            Icon(Icons.Default.Search, contentDescription = "Suchen")
        },
        trailingIcon = {
            if (query.isNotEmpty()) {
                IconButton(onClick = onClearClick) {
                    Icon(Icons.Default.Close, contentDescription = "Suche löschen")
                }
            }
        },
        singleLine = true
    )
}

@Composable
private fun FilterChipRow(
    uiState: ItemListUiState,
    onCategorySelected: (Int?) -> Unit,
    onLocationSelected: (Int?) -> Unit,
    onExpirySelected: (ExpiryFilter?) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState())
            .padding(horizontal = 16.dp, vertical = 4.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        FilterDropdownChip(
            label = "Kategorie",
            selectedLabel = uiState.availableCategories
                .find { it.first == uiState.selectedCategoryId }?.second,
            options = uiState.availableCategories,
            onOptionSelected = { onCategorySelected(it) },
            onClear = { onCategorySelected(null) }
        )

        FilterDropdownChip(
            label = "Lagerort",
            selectedLabel = uiState.availableLocations
                .find { it.first == uiState.selectedLocationId }?.second,
            options = uiState.availableLocations,
            onOptionSelected = { onLocationSelected(it) },
            onClear = { onLocationSelected(null) }
        )

        FilterDropdownChip(
            label = "Ablauf",
            selectedLabel = uiState.selectedExpiryFilter?.label,
            options = ExpiryFilter.entries.map { it.ordinal to it.label },
            onOptionSelected = { ordinal ->
                onExpirySelected(ExpiryFilter.entries[ordinal])
            },
            onClear = { onExpirySelected(null) }
        )
    }
}

@Composable
private fun FilterDropdownChip(
    label: String,
    selectedLabel: String?,
    options: List<Pair<Int, String>>,
    onOptionSelected: (Int) -> Unit,
    onClear: () -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    val isSelected = selectedLabel != null

    Box {
        FilterChip(
            selected = isSelected,
            onClick = { expanded = true },
            label = {
                Text(if (isSelected) "$label: $selectedLabel" else label)
            },
            trailingIcon = {
                Icon(
                    imageVector = Icons.Default.ArrowDropDown,
                    contentDescription = null,
                    modifier = Modifier.size(18.dp)
                )
            }
        )
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            if (isSelected) {
                DropdownMenuItem(
                    text = { Text("Alle") },
                    onClick = {
                        expanded = false
                        onClear()
                    }
                )
            }
            options.forEach { (id, name) ->
                DropdownMenuItem(
                    text = { Text(name) },
                    onClick = {
                        expanded = false
                        onOptionSelected(id)
                    }
                )
            }
        }
    }
}

@Composable
private fun NoFilterResultsState(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "Keine Items gefunden",
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun DeleteItemDialog(
    itemName: String,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Artikel löschen?") },
        text = {
            Text("Möchten Sie den Artikel \"$itemName\" wirklich löschen?")
        },
        confirmButton = {
            TextButton(onClick = onConfirm) {
                Text(
                    "Löschen",
                    color = MaterialTheme.colorScheme.error
                )
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Abbrechen")
            }
        }
    )
}
