@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.composable

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
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.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.PopupProperties
import eu.gaudian.translator.R

/**
 * A modern, custom dropdown menu composable that provides a styled text field with a dropdown list of options.
 * This implementation uses a custom dropdown for a more tailored look compared to the stock menu, behaving like a normal ExposedDropdownMenu.
 * Allows managing selection and expansion, making it a convenient wrapper for dropdowns.
 *
 * @param expanded Whether the dropdown menu is expanded.
 * @param onDismissRequest Callback invoked when the dropdown menu should be dismissed.
 * @param modifier Modifier for the composable.
 * @param label Composable for the label displayed in the text field.
 * @param enabled Whether the dropdown is enabled.
 * @param placeholder Optional placeholder text when no option is selected.
 * @param selectedText The text to display in the text field for the selected option.
 * @param onExpandRequest Callback invoked when the dropdown should expand.
 * @param content Composable content for the dropdown items, typically using AppDropdownMenuItem.
 */
@Composable
fun AppDropdownMenu(
    expanded: Boolean,
    onDismissRequest: () -> Unit,
    modifier: Modifier = Modifier,
    label: @Composable (() -> Unit)? = null,
    enabled: Boolean = true,
    placeholder: @Composable (() -> Unit)? = null,
    selectedText: String = "",
    onExpandRequest: () -> Unit = {},
    content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit,
) {
    var textFieldSize by remember { mutableStateOf(Size.Zero) }
    val interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }

    Column(modifier = modifier) {
        OutlinedTextField(
            value = selectedText,
            onValueChange = {},
            modifier = Modifier
                .fillMaxWidth()
                .onGloballyPositioned { coordinates ->
                    textFieldSize = coordinates.size.toSize()
                }
                .clickable(
                    enabled = enabled,
                    onClick = onExpandRequest,
                    interactionSource = interactionSource,
                    indication = null
                ),
            readOnly = true,
            label = label,
            placeholder = placeholder,
            trailingIcon = {
                val icon = if (expanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown
                Icon(
                    imageVector = icon,
                    contentDescription = if (expanded) stringResource(R.string.cd_collapse) else stringResource(R.string.cd_expand),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            },
            shape = ComponentDefaults.DefaultShape,
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = MaterialTheme.colorScheme.primary,
                unfocusedBorderColor = MaterialTheme.colorScheme.onSurface.copy(alpha = ComponentDefaults.ALPHA_LOW),
                focusedLabelColor = MaterialTheme.colorScheme.primary,
                cursorColor = MaterialTheme.colorScheme.primary,
                disabledBorderColor = MaterialTheme.colorScheme.onSurface.copy(alpha = ComponentDefaults.ALPHA_LOW),
                disabledLabelColor = MaterialTheme.colorScheme.onSurface.copy(alpha = ComponentDefaults.ALPHA_MEDIUM)
            ),
            enabled = enabled,
            interactionSource = interactionSource
        )

        DropdownMenu(
            expanded = expanded,
            onDismissRequest = onDismissRequest,
            modifier = Modifier
                .width(with(LocalDensity.current) { textFieldSize.width.toDp() })
                // Give the menu itself a bit of breathing room
                .padding(vertical = 4.dp),
            offset = DpOffset(0.dp, 4.dp), // Slight detachment from the anchor
            scrollState = rememberScrollState(),
            properties = PopupProperties(focusable = true),
            shape = RoundedCornerShape(12.dp),
            containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
            tonalElevation = 6.dp,
            shadowElevation = 8.dp,
            border = BorderStroke(0.5.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
        ) {
            content()
        }
    }
}

/**
 * A modern and stylish composable for individual dropdown items, featuring enhanced visual design
 * with subtle shadows, rounded corners, and smooth interactions.
 */
@Composable
fun AppDropdownMenuItem(
    text: @Composable () -> Unit,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    selected: Boolean = false,
) {
    val contentColor = if (enabled) {
        if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
    } else {
        MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
    }

    // Modern "floating" highlight background
    val backgroundColor = if (selected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f) else Color.Transparent

    Box(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp, vertical = 2.dp) // Outer padding creates the floating shape
            .clip(RoundedCornerShape(8.dp))
            .background(backgroundColor)
            .clickable(enabled = enabled) { onClick() }
            //.padding(horizontal = 12.dp, vertical = 10.dp) // Inner padding keeps content comfortable
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            leadingIcon?.invoke()
            if (leadingIcon != null) {
                Spacer(modifier = Modifier.width(12.dp))
            }
            Box(modifier = Modifier.weight(1f)) {
                CompositionLocalProvider(LocalContentColor provides contentColor) {
                    text()
                }
            }
            if (trailingIcon != null) {
                Spacer(modifier = Modifier.width(12.dp))
                trailingIcon()
            }
        }
    }
}

// ... [Previews remain exactly the same as your original file] ...

@Composable
fun <T> LargeDropdownMenu(
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    label: String,
    notSetLabel: String? = null,
    items: List<T>,
    selectedIndex: Int = -1,
    onItemSelected: (index: Int, item: T) -> Unit,
    selectedItemToString: (T) -> String = { it.toString() },
    drawItem: @Composable (T, Boolean, Boolean, () -> Unit) -> Unit = { item, selected, itemEnabled, onClick ->
        LargeDropdownMenuItem(
            text = item.toString(),
            selected = selected,
            enabled = itemEnabled,
            onClick = onClick,
        )
    },
) {
    var expanded by remember { mutableStateOf(false) }

    Box(modifier = modifier.height(IntrinsicSize.Min)) {
        OutlinedTextField(
            label = { Text(label) },
            value = items.getOrNull(selectedIndex)?.let { selectedItemToString(it) } ?: "",
            enabled = enabled,
            modifier = Modifier.fillMaxWidth(),
            trailingIcon = {
                val icon: ImageVector = if (expanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown
                Icon(icon, contentDescription = "")
            },
            onValueChange = { },
            readOnly = true,
        )

        Surface(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 8.dp)
                .clip(MaterialTheme.shapes.extraSmall)
                .clickable(enabled = enabled) { expanded = true },
            color = Color.Transparent,
        ) {}
    }

    if (expanded) {
        Dialog(
            onDismissRequest = { expanded = false }, // Fixed bug from original code
        ) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = MaterialTheme.colorScheme.surfaceContainerHigh,
                shadowElevation = 8.dp,
                tonalElevation = 6.dp
            ) {
                val listState = rememberLazyListState()
                if (selectedIndex > -1) {
                    LaunchedEffect("ScrollToSelected") {
                        listState.scrollToItem(index = selectedIndex)
                    }
                }

                // Added vertical padding to the list instead of hard dividers
                LazyColumn(
                    modifier = Modifier.fillMaxWidth(),
                    state = listState,
                    contentPadding = PaddingValues(vertical = 8.dp)
                ) {
                    if (notSetLabel != null) {
                        item {
                            LargeDropdownMenuItem(
                                text = notSetLabel,
                                selected = false,
                                enabled = false,
                                onClick = { },
                            )
                        }
                    }
                    itemsIndexed(items) { index, item ->
                        val selectedItem = index == selectedIndex
                        drawItem(
                            item,
                            selectedItem,
                            true
                        ) {
                            onItemSelected(index, item)
                            expanded = false
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun LargeDropdownMenuItem(
    text: String,
    selected: Boolean,
    enabled: Boolean,
    onClick: () -> Unit,
) {
    val contentColor = when {
        !enabled -> MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
        selected -> MaterialTheme.colorScheme.primary
        else -> MaterialTheme.colorScheme.onSurface
    }

    val backgroundColor = if (selected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f) else Color.Transparent
    val fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal

    CompositionLocalProvider(LocalContentColor provides contentColor) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp, vertical = 4.dp) // Outer padding for floating shape
                .clip(RoundedCornerShape(8.dp))
                .background(backgroundColor)
                .clickable(enabled) { onClick() }
                .padding(horizontal = 16.dp, vertical = 14.dp) // Inner padding
        ) {
            Text(
                text = text,
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = fontWeight),
            )
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun LargeDropdownMenuItemPreview() {
    LargeDropdownMenuItem(
        text = "Sample Item",
        selected = false,
        enabled = true,
        onClick = {}
    )
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun LargeDropdownMenuItemSelectedPreview() {
    LargeDropdownMenuItem(
        text = "Selected Item",
        selected = true,
        enabled = true,
        onClick = {}
    )
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun LargeDropdownMenuPreview() {
    val options = listOf("Option 1", "Option 2", "Option 3", "Option 4", "Option 5")
    var selectedIndex by remember { mutableIntStateOf(1) }

    LargeDropdownMenu(
        label = "Select Option",
        items = options,
        selectedIndex = selectedIndex,
        onItemSelected = { index, _ ->
            selectedIndex = index
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun LargeDropdownMenuExpandedPreview() {
    val options = listOf("Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6")
    var selectedIndex by remember { mutableIntStateOf(2) }

    // Simulate expanded state by showing the dropdown and the dialog content
    Column {
        LargeDropdownMenu(
            label = "Select Option",
            items = options,
            selectedIndex = selectedIndex,
            onItemSelected = { index, _ ->
                selectedIndex = index
            }
        )

        // Manually show the expanded dialog content for preview
        Dialog(onDismissRequest = {}) {
            Surface(shape = RoundedCornerShape(12.dp)) {
                val listState = rememberLazyListState()
                LaunchedEffect("ScrollToSelected") {
                    listState.scrollToItem(index = selectedIndex)
                }

                LazyColumn(modifier = Modifier.fillMaxWidth(), state = listState) {
                    itemsIndexed(options) { index, item ->
                        LargeDropdownMenuItem(
                            text = item,
                            selected = index == selectedIndex,
                            enabled = true,
                            onClick = { selectedIndex = index }
                        )

                        if (index < options.lastIndex) {
                            HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
                        }
                    }
                }
            }
        }
    }
}