package eu.gaudian.translator.view.translation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
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.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons

@Composable
fun OutputCard(
    modifier: Modifier = Modifier,
    text: String,
    explanationText: String? = null,
    isExplanationOn: Boolean = false,
    isPlayEnabled: Boolean = false,
    translationSource: String? = null,
    translationModel: String? = null,
    onCopyClick: () -> Unit,
    onPlayClick: () -> Unit,
    onShareClick: () -> Unit,
    onAddToDictionaryClick: () -> Unit,
    onExplanationToggle: () -> Unit,
    onRequestAlternatives: (String, (Result<List<String>>) -> Unit) -> Unit,
    onApplyAlternative: (originalWord: String, chosen: String) -> Unit
) {
    AppCard(
        modifier = modifier
            .fillMaxWidth()
            .padding(0.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState())
                    .padding(8.dp),
                contentAlignment = if (text.isEmpty()) Alignment.Center else Alignment.TopStart
            ) {
                if (text.isEmpty()) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center,
                        modifier = Modifier.alpha(0.3f)
                    ) {
                        Icon(
                            imageVector = AppIcons.Translate,
                            contentDescription = null,
                            modifier = Modifier.size(48.dp),
                            tint = MaterialTheme.colorScheme.onSurface
                        )
                        Text(
                            text = stringResource(R.string.text_translation_will_appear_here),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                } else {
                    Column {
                        if (!translationSource.isNullOrBlank()) {
                            val sourceInfo = if (!translationModel.isNullOrBlank()) {
                                translationModel
                            } else {
                                translationSource
                            }
                            Text(
                                text = sourceInfo,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary,
                                modifier = Modifier
                                    .padding(bottom = 8.dp)
                                    .background(
                                        color = MaterialTheme.colorScheme.primary.copy(alpha = 0.16f),
                                        shape = RoundedCornerShape(999.dp)
                                    )
                                    .padding(horizontal = 10.dp, vertical = 4.dp)
                            )
                        }

                        ClickableTranslatedText(
                            text = text,
                            onWordClick = { word ->
                                onRequestAlternatives(word) { _ -> }
                            },
                            onRequestAlternatives = onRequestAlternatives,
                            onApplyAlternative = onApplyAlternative
                        )

                        if (isExplanationOn && !explanationText.isNullOrBlank()) {
                            Text(
                                text = stringResource(R.string.text_explanation) + ":\n" + explanationText,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                modifier = Modifier.padding(top = 8.dp)
                            )
                        }
                    }
                }
            }

            val hasText = text.isNotEmpty()
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(0.dp, bottom = 0.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ) {

                ActionBar(
                    contentHorizontalArrangement = Arrangement.Start
                ) {
                    IconButton(onClick = onPlayClick, enabled = isPlayEnabled) {
                        Icon(
                            imageVector = AppIcons.TextToSpeech,
                            contentDescription = stringResource(R.string.play_audio),
                            tint = if (isPlayEnabled && hasText) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                    IconButton(onClick = onCopyClick, enabled = hasText) {
                        Icon(
                            imageVector = AppIcons.Copy,
                            contentDescription = stringResource(R.string.copy_text),
                            tint = if (hasText) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                }

                Spacer(modifier = Modifier.width(4.dp))

                ExpandableActionBar {
                    IconButton(onClick = onShareClick, enabled = hasText) {
                        Icon(
                            imageVector = AppIcons.Share,
                            contentDescription = stringResource(R.string.share_text),
                            tint = if (hasText) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                    IconButton(onClick = onAddToDictionaryClick, enabled = hasText) {
                        Icon(
                            imageVector = AppIcons.AddToDictionary,
                            contentDescription = stringResource(R.string.label_add_to_dictionary),
                            tint = if (hasText) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                    IconButton(onClick = onExplanationToggle, enabled = hasText) {
                        Icon(
                            imageVector = AppIcons.Info,
                            contentDescription = stringResource(R.string.text_explanation),
                            tint = if (hasText) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                }
            }
        }
    }
}

@Suppress("LocalVariableName")
@Composable
private fun ClickableTranslatedText(
    text: String,
    onWordClick: (word: String) -> Unit,
    onRequestAlternatives: (String, (Result<List<String>>) -> Unit) -> Unit,
    onApplyAlternative: (originalWord: String, chosen: String) -> Unit
) {
    val tokens = remember(text) {
        val builder = mutableListOf<String>()
        if (text.isEmpty()) builder
        else {
            val sb = StringBuilder()
            val KIND_SPACE = 0
            val KIND_WORD = 1
            val KIND_OTHER = 2
            fun Char.isJoinerOrMark(): Boolean =
                this == '\u200D' || this == '\u200C' ||
                        this == '\u09CD' || this == '\u094D' ||
                        this == '\u0BCD' ||
                        run {
                            val t = Character.getType(this)
                            t == Character.NON_SPACING_MARK.toInt() || t == Character.COMBINING_SPACING_MARK.toInt() || t == Character.ENCLOSING_MARK.toInt()
                        }
            fun kindOf(ch: Char): Int = when {
                ch.isWhitespace() -> KIND_SPACE
                ch.isLetterOrDigit() || ch.isJoinerOrMark() -> KIND_WORD
                else -> KIND_OTHER
            }
            var currentKind: Int? = null
            for (ch in text) {
                val k = kindOf(ch)
                if (currentKind == null) {
                    currentKind = k
                    sb.append(ch)
                } else if (k == currentKind || (currentKind == KIND_WORD && (ch.isJoinerOrMark() || ch.isLetterOrDigit()))) {
                    sb.append(ch)
                } else {
                    builder.add(sb.toString())
                    sb.clear()
                    sb.append(ch)
                    currentKind = k
                }
            }
            if (sb.isNotEmpty()) builder.add(sb.toString())
            builder
        }
    }

    var popupOpen by remember { mutableStateOf(false) }
    var selectedWord by remember { mutableStateOf<String?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    var alternatives by remember { mutableStateOf<List<String>>(emptyList()) }

    LaunchedEffect(popupOpen) {
        if (!popupOpen) selectedWord = null
    }

    Box {
        FlowRow(horizontalArrangement = Arrangement.Start) {
            tokens.forEach { token ->
                val isWord = token.any { it.isLetterOrDigit() }
                val isSelected = isWord && token == selectedWord && popupOpen

                var wordHeight by remember { mutableIntStateOf(0) }

                Box(
                    modifier = Modifier.onSizeChanged { wordHeight = it.height }
                ) {
                    if (isWord) {
                        Text(
                            text = token,
                            style = MaterialTheme.typography.titleLarge,
                            color = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier
                                .padding(horizontal = 0.dp)
                                .clip(RoundedCornerShape(4.dp))
                                .background(if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent)
                                .clickable {
                                    selectedWord = token
                                    popupOpen = true
                                    isLoading = true
                                    onRequestAlternatives(token) { result ->
                                        isLoading = false
                                        result.onSuccess { alternatives = it }
                                            .onFailure { alternatives = emptyList() }
                                    }
                                    onWordClick(token)
                                }
                                .padding(horizontal = 2.dp)
                        )

                        if (isSelected) {
                            Popup(
                                alignment = Alignment.TopCenter,
                                offset = IntOffset(0, wordHeight + 10), // +10 for small visual gap
                                onDismissRequest = { popupOpen = false },
                                properties = PopupProperties(focusable = true)
                            ) {
                                Card(
                                    elevation = CardDefaults.cardElevation(4.dp),
                                    shape = RoundedCornerShape(12.dp),
                                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHighest),
                                    modifier = Modifier
                                        .widthIn(min = 150.dp, max = 250.dp)
                                ) {
                                    Column(
                                        modifier = Modifier.padding(8.dp),
                                        verticalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Text(
                                            text = stringResource(R.string.label_alternatives_for, token),
                                            style = MaterialTheme.typography.labelSmall,
                                            color = MaterialTheme.colorScheme.primary,
                                            modifier = Modifier.padding(bottom = 4.dp, start = 8.dp)
                                        )

                                        if (isLoading) {
                                            Box(Modifier
                                                .fillMaxWidth()
                                                .padding(16.dp), contentAlignment = Alignment.Center) {
                                                CircularProgressIndicator(modifier = Modifier.size(24.dp))
                                            }
                                        } else if (alternatives.isEmpty()) {
                                            Text(
                                                text = stringResource(id = R.string.not_available),
                                                style = MaterialTheme.typography.bodySmall,
                                                modifier = Modifier.padding(8.dp)
                                            )
                                        } else {
                                            alternatives.take(5).forEach { alt ->
                                                Row(
                                                    modifier = Modifier
                                                        .fillMaxWidth()
                                                        .clip(RoundedCornerShape(8.dp))
                                                        .clickable {
                                                            onApplyAlternative(token, alt)
                                                            popupOpen = false
                                                        }
                                                        .padding(horizontal = 8.dp, vertical = 8.dp),
                                                    verticalAlignment = Alignment.CenterVertically
                                                ) {
                                                    Text(
                                                        text = alt,
                                                        style = MaterialTheme.typography.bodyMedium
                                                    )
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        Text(
                            text = token,
                            style = MaterialTheme.typography.headlineSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@ThemePreviews
@Composable
fun OutputCardPreview() {
    OutputCard(
        text = stringResource(R.string.this_is_a_sample_output_text),
        explanationText = "This is an explanation.",
        isExplanationOn = true,
        translationSource = "AI Model",
        translationModel = "GPT-4",
        onCopyClick = {},
        onPlayClick = {},
        onShareClick = {},
        onAddToDictionaryClick = {},
        onExplanationToggle = {},
        onRequestAlternatives = { _, cb -> cb(Result.success(listOf("option1", "option2"))) },
        onApplyAlternative = { _, _ -> }
    )
}