package eu.gaudian.translator.view.dictionary

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
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.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.grammar.VerbConjugation
import eu.gaudian.translator.view.composable.AppIcons

@Composable
fun VerbTable(
    conjugation: VerbConjugation,
    modifier: Modifier = Modifier
) {
    val tenses = conjugation.conjugations.keys.toList()
    val expandedStates = remember {
        mutableStateMapOf<String, Boolean>().apply {
            tenses.firstOrNull()?.let { this[it] = true }
        }
    }

    Card(
        modifier = modifier.fillMaxWidth(),
        shape = UnifiedCornerShape, // Using the shared shape
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceContainerLow
                ?: MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
        ),
        elevation = CardDefaults.cardElevation(0.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // Title
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(bottom = 12.dp)
            ) {
                Icon(
                    imageVector = AppIcons.Check, // Or a generic Verb icon
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.padding(end = 8.dp).width(18.dp)
                )
                Text(
                    text = stringResource(R.string.label_conjugation, conjugation.infinitive),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }

            tenses.forEach { tense ->
                val forms = conjugation.conjugations[tense] ?: emptyList()
                val isExpanded = expandedStates[tense] == true

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 4.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(if(isExpanded) MaterialTheme.colorScheme.surface.copy(alpha=0.5f) else androidx.compose.ui.graphics.Color.Transparent)
                ) {
                    // Expandable tense header
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { expandedStates[tense] = !isExpanded }
                            .padding(horizontal = 8.dp, vertical = 12.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = tense,
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = if(isExpanded) FontWeight.Bold else FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        Icon(
                            imageVector = if (isExpanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }

                    // Conjugation forms
                    AnimatedVisibility(
                        visible = isExpanded,
                        enter = expandVertically() + fadeIn(),
                        exit = shrinkVertically() + fadeOut()
                    ) {
                        Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
                            val count = maxOf(conjugation.pronouns.size, forms.size)
                            for (i in 0 until count) {
                                val person = conjugation.pronouns.getOrNull(i) ?: ""
                                val form = forms.getOrNull(i) ?: ""

                                if (form.isNotBlank()) {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 4.dp),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        if (person.isNotBlank()) {
                                            Text(
                                                text = person,
                                                modifier = Modifier.width(100.dp),
                                                style = MaterialTheme.typography.bodyMedium,
                                                color = MaterialTheme.colorScheme.secondary
                                            )
                                        }
                                        Text(
                                            text = form,
                                            modifier = Modifier.weight(1f),
                                            style = MaterialTheme.typography.bodyMedium,
                                            fontWeight = FontWeight.SemiBold,
                                            color = MaterialTheme.colorScheme.onSurface
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                if (tense != tenses.last()) {
                    HorizontalDivider(
                        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f),
                        modifier = Modifier.padding(horizontal = 8.dp)
                    )
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun VerbTablePreview() {
    val sampleConjugation = VerbConjugation(
        infinitive = "être",
        conjugations = mapOf(
            "Présent" to listOf("suis", "es", "est", "sommes", "êtes", "sont"),
            "Imparfait" to listOf("étais", "étais", "était", "étions", "étiez", "étaient")
        )
    )
    VerbTable(conjugation = sampleConjugation)
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun VerbTableGermanPreview() {
    val sampleConjugation = VerbConjugation(
        infinitive = "laufen",
        pronouns = listOf("ich", "du", "er/sie/es", "wir", "ihr", "sie"),
        conjugations = mapOf(
            "Präsens" to listOf("laufe", "läufst", "läuft", "laufen", "lauft", "laufen"),
            "Präteritum" to listOf("lief", "liefst", "lief", "liefen", "lieft", "liefen")
        )
    )
    VerbTable(conjugation = sampleConjugation)
}