@file:Suppress("SameParameterValue")

package eu.gaudian.translator.view.dictionary

import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
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.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AutoResizeSingleLineText

// A shared constant for consistency across the app
val UnifiedCornerShape = RoundedCornerShape(16.dp)

@Composable
fun <T> DictionaryTableCard(
    items: List<T>,
    modifier: Modifier = Modifier,
    cornerRadius: Dp = 16.dp, // Modernized radius
    maxRowsBeforeCollapse: Int = 6,
    headerContent: @Composable RowScope.() -> Unit,
    rowContent: @Composable RowScope.(T) -> Unit
) {
    val maxDataRows = maxRowsBeforeCollapse - 1
    val isCollapsible = items.size > maxDataRows
    var isExpanded by remember { mutableStateOf(false) }

    val visibleItems = if (isCollapsible && !isExpanded) items.take(maxDataRows) else items

    Card(
        modifier = modifier
            .fillMaxWidth()
            .animateContentSize(),
        shape = RoundedCornerShape(cornerRadius),
        // Switch to a filled surface variant for a modern "block" look, removing borders
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceContainerLow
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
    ) {
        Column {
            // Header with distinct background
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f))
                    .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically,
                content = headerContent
            )

            // Rows
            visibleItems.forEachIndexed { index, item ->
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 12.dp)
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        content = { rowContent(item) }
                    )
                }
                // Subtle divider between rows, but not after the last one unless footer exists
                if (index < visibleItems.lastIndex || isCollapsible) {
                    HorizontalDivider(
                        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f),
                        modifier = Modifier.padding(horizontal = 16.dp)
                    )
                }
            }

            // Footer
            if (isCollapsible) {
                DictionaryTableFooter(
                    isExpanded = isExpanded,
                    remainingCount = items.size - maxDataRows,
                    onToggle = { isExpanded = !isExpanded }
                )
            }
        }
    }
}

@Composable
fun DictionaryTableFooter(
    isExpanded: Boolean,
    remainingCount: Int,
    onToggle: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onToggle() }
            .padding(12.dp),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = if (isExpanded) stringResource(R.string.label_show_less) else stringResource(
                R.string.label_show_2d_more,
                remainingCount
            ),
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.primary,
            fontWeight = FontWeight.Bold
        )
        Spacer(modifier = Modifier.width(4.dp))
        Icon(
            imageVector = if (isExpanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(16.dp)
        )
    }
}

// --- Unchanged Layout Helpers (Same as previous step) ---

@Composable
fun DictionaryTableHeaderRow(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(MaterialTheme.colorScheme.surfaceVariant)
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        content = content
    )
}

@Composable
fun DictionaryTableRow(
    modifier: Modifier = Modifier,
    showDivider: Boolean = true,
    content: @Composable RowScope.() -> Unit
) {
    if (showDivider) {
        HorizontalDivider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)
    }
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        content = content
    )
}

@Composable
fun RowScope.DictionaryTableHeaderCell(
    text: String,
    modifier: Modifier = Modifier,
    weight: Float = 1f
) {
    Text(
        text = text.uppercase(),
        style = MaterialTheme.typography.labelSmall,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        fontWeight = FontWeight.Bold,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
        modifier = modifier.weight(weight)
    )
}

@Composable
fun RowScope.DictionaryTableCell(
    text: String,
    modifier: Modifier = Modifier,
    weight: Float = 1f,
    isItalic: Boolean = false
) {
    val baseStyle = MaterialTheme.typography.bodyMedium
    val finalStyle = if (isItalic) baseStyle.copy(fontStyle = FontStyle.Italic) else baseStyle

    AutoResizeSingleLineText(
        text = text,
        style = finalStyle,
        modifier = modifier.weight(weight),
        color = MaterialTheme.colorScheme.onSurface
    )
}


// Simple data class for preview purposes
data class WordEntry(val word: String, val translation: String, val type: String)

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun DictionaryTableCardCollapsiblePreview() {
    // Define column weights
    val w1 = .35f; val w2 = .35f; val w3 = .3f

    // Create a list with 6 items (Header + 6 = 7 lines total -> Should Collapse)
    val entries = listOf(
        WordEntry("hello", "hola", "noun"),
        WordEntry("world", "mundo", "noun"),
        WordEntry("cat", "gato", "noun"), // Item 3 (Line 4)
        WordEntry("dog", "perro", "noun"), // Item 4 (Line 5) -> Hidden
        WordEntry("red", "rojo", "adj"),
        WordEntry("blue", "azul", "adj")
    )

    Column(modifier = Modifier.padding(16.dp)) {
        Text("Collapsible Table (Limit: 4 lines)", style = MaterialTheme.typography.titleMedium)
        Spacer(modifier = Modifier.height(8.dp))

        DictionaryTableCard(
            items = entries,
            maxRowsBeforeCollapse = 7, // Header +  items
            headerContent = {
                DictionaryTableHeaderCell("Word", weight = w1)
                DictionaryTableHeaderCell("Translation", weight = w2)
                DictionaryTableHeaderCell("Type", weight = w3)
            }
        ) { item ->
            // This block runs for every item in the list
            DictionaryTableCell(item.word, weight = w1)
            DictionaryTableCell(item.translation, weight = w2)
            DictionaryTableCell(item.type, weight = w3, isItalic = true)
        }
    }
}