package eu.gaudian.translator.view.composable

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
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.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.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.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.res.stringResource
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 eu.gaudian.translator.R
import kotlinx.coroutines.delay

/**
 * Helper composable for consistent OutlinedTextField colors.
 */
@Composable
private fun appTextFieldColors() = OutlinedTextFieldDefaults.colors(
    focusedBorderColor = MaterialTheme.colorScheme.primary,
    unfocusedBorderColor = MaterialTheme.colorScheme.onSurface.copy(alpha = ComponentDefaults.ALPHA_LOW),
    focusedLabelColor = MaterialTheme.colorScheme.primary,
    cursorColor = MaterialTheme.colorScheme.primary
)

/**
 * A styled text input field.
 *
 * @param value The input text to be shown in the text field.
 * @param onValueChange The callback that is triggered when the input service updates the text.
 * @param modifier The modifier to be applied to the text field.
 * @param label A composable lambda for the label to be displayed inside the text field.
 * @param trailingIcon A composable lambda for the trailing icon.
 * @param paste Controls the visibility of the paste icon.
 * @param clear Controls the visibility of the clear icon.
 */
@Composable
fun AppOutlinedTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    singleLine: Boolean = false,
    minLines: Int = 1,
    maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
    placeholder: @Composable (() -> Unit)? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    leadingIcon: @Composable (() -> Unit)? = null,
    paste: Boolean = false,
    clear: Boolean = false,
    supportingText: @Composable (() -> Unit)? = null,
) {
    val clipboardManager = LocalClipboardManager.current

    val finalTrailingIcon: @Composable (() -> Unit)? = if (paste || clear || trailingIcon != null) {
        {
            Row(verticalAlignment = Alignment.CenterVertically) {
                if (paste && value.isEmpty()) {
                    IconButton(onClick = { onValueChange(clipboardManager.getText()?.text ?: "") }) {
                        Icon(
                            imageVector = AppIcons.Paste,
                            contentDescription = stringResource(R.string.cd_paste),
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
                if (clear && value.isNotEmpty()) {
                    IconButton(onClick = { onValueChange("") }) {
                        Icon(
                            imageVector = AppIcons.Clear,
                            contentDescription = stringResource(R.string.label_clear),
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
                if (trailingIcon != null) {
                    trailingIcon()
                }
            }
        }
    } else {
        null
    }

    OutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier.fillMaxWidth(),
        label = label,
        trailingIcon = finalTrailingIcon,
        shape = ComponentDefaults.DefaultShape,
        colors = appTextFieldColors(),
        placeholder = placeholder,
        enabled = enabled,
        readOnly = readOnly,
        leadingIcon = leadingIcon,
        minLines = minLines,
        maxLines = maxLines,
        supportingText = supportingText,
    )
}

@Composable
fun InspiringSearchField(
    value: String,
    hints : Array<String>,
    onValueChange: (String) -> Unit,
    minLines: Int = 1,
    maxLines: Int = 1,
    enabled: Boolean = true
) {

    var currentHintIndex by remember { mutableIntStateOf(0) }

    // Start rotating immediately when the dialog appears
    LaunchedEffect(hints) {
        if (hints.isNotEmpty()) {
            while (true) {
                delay(2800)
                currentHintIndex = (currentHintIndex + 1) % hints.size
            }
        }
    }

    AppOutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        //label = { Text(stringResource(R.string.text_search_term)) },
        modifier = Modifier.fillMaxWidth(),
        placeholder = {
            AnimatedContent(
                targetState = if (hints.isNotEmpty()) hints[currentHintIndex] else "",
                transitionSpec = {
                    (fadeIn(tween(400)) + slideInVertically { it / 2 })
                        .togetherWith(fadeOut(tween(400)) + slideOutVertically { -it / 2 })
                },
                label = "HintAnimation"
            ) { hint ->
                Text(
                    text = hint,
                    color = Color.Gray.copy(alpha = 0.6f),
                    //maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        },
        singleLine = true,
        minLines = minLines,
        maxLines = maxLines,
        enabled = enabled
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppOutlinedTextFieldPreview() {
    var text by remember { mutableStateOf("Test") }
    AppOutlinedTextField(
        value = text,
        onValueChange = { },
        label = { Text(stringResource(R.string.email_address)) }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "Search Field Preview")
@Composable
fun PreviewInspiringSearchField() {
    MaterialTheme {
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = Color(0xFFF8F9FA) // Light gray background like in your screenshot
        ) {
            Column(
                modifier = Modifier
                    .padding(24.dp)
                    .fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "Deixe a IA encontrar\nvocabulário para você!",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold
                )

                // Our animated component
                InspiringSearchField(
                    value = "Test",
                    hints = listOf("test1", "test2", "test3").toTypedArray(),
                    onValueChange = {}
                )

                // Placeholder for the rest of your UI
                Button(
                    onClick = { },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text("Continuar")
                }
            }
        }
    }
}