package eu.gaudian.translator.view.translation

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
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.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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
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.sp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.TranslationHistoryItem
import eu.gaudian.translator.model.generateRandomLanguage
import eu.gaudian.translator.model.generateSimpleLanguage
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.TranslationViewModel

@Composable
fun HistorySheetContent(
    translationViewModel: TranslationViewModel,
    languageViewModel: LanguageViewModel,
    onPlayAudio: (text: String, language: Language) -> Unit,
    onItemClick: (TranslationHistoryItem) -> Unit
) {

    val history by translationViewModel.translationHistory.collectAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surface) // Clean background
            .padding(bottom = 16.dp)
    ) {
        // --- Custom Header ---
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 24.dp, horizontal = 16.dp) // Added outer padding
        ) {
            // 1. Calculate a safe padding for the title so it never touches the delete button
            // "Delete All" usually takes about 60-80dp. We use 80dp to be safe.
            val titlePadding = if (history.isNotEmpty()) 80.dp else 0.dp

            Text(
                text = stringResource(R.string.cd_translation_history),
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    // FIX: This padding ensures the title wraps before hitting the button
                    .padding(horizontal = titlePadding)
                    .fillMaxWidth()
            )

            if (history.isNotEmpty()) {
                Text(
                    text = stringResource(R.string.label_delete_all),
                    style = MaterialTheme.typography.labelLarge,
                    color = MaterialTheme.colorScheme.error,
                    modifier = Modifier
                        .clip(RoundedCornerShape(8.dp))
                        .clickable { translationViewModel.clearTranslationHistory() }
                        .padding(8.dp) // Touch target padding
                )
            }
        }

        if (history.isEmpty()) {
            EmptyHistoryState()
        } else {
            LazyColumn(
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                modifier = Modifier.fillMaxSize()
            ) {
                itemsIndexed(
                    items = history,
                    key = { _, item -> item.id }
                ) { _, item ->
                    val sourceLanguage by languageViewModel.getLanguageByIdFlow(item.sourceLanguageCode).collectAsState(initial = null)
                    val targetLanguage by languageViewModel.getLanguageByIdFlow(item.targetLanguageCode).collectAsState(initial = null)



                    sourceLanguage?.let {
                        targetLanguage?.let { onClick ->
                            SwipeableHistoryItem(
                                item = item,
                                onDelete = { translationViewModel.deleteTranslationHistoryItem(item) },
                                onPlay = onPlayAudio,
                                onClick = onItemClick,
                                sourceLanguage = it,
                                targetLanguage = onClick,

                                )
                        }
                    }


                }
            }
        }
    }
}

@Composable
fun EmptyHistoryState() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(bottom = 64.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = AppIcons.History,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.surfaceVariant,
            modifier = Modifier.size(80.dp)
        )
        Spacer(modifier = Modifier.size(16.dp))
        Text(
            text = stringResource(R.string.label_no_history_yet),
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
fun SwipeableHistoryItem(
    item: TranslationHistoryItem,
    sourceLanguage: Language,
    targetLanguage: Language,
    onDelete: () -> Unit,
    onPlay: (text: String, language: Language) -> Unit,
    onClick: (TranslationHistoryItem) -> Unit
) {

    val dismissState = rememberSwipeToDismissBoxState(

        confirmValueChange = {
            if (it == SwipeToDismissBoxValue.EndToStart || it == SwipeToDismissBoxValue.StartToEnd) {
                onDelete()
                true
            }
            else {
                false
            }
        }
    )

    SwipeToDismissBox(
        state = dismissState,
        enableDismissFromStartToEnd = false,
        backgroundContent = {
            val color by animateColorAsState(
                if (dismissState.targetValue == SwipeToDismissBoxValue.EndToStart) MaterialTheme.colorScheme.errorContainer else Color.Transparent,
                label = "bgColor"
            )
            val iconScale by animateFloatAsState(
                if (dismissState.targetValue == SwipeToDismissBoxValue.EndToStart) 1.2f else 0.8f,
                label = "iconScale"
            )

            Box(
                Modifier
                    .fillMaxSize()
                    .clip(RoundedCornerShape(16.dp))
                    .background(color)
                    .padding(horizontal = 24.dp),
                contentAlignment = Alignment.CenterEnd
            ) {
                Icon(
                    AppIcons.Delete,
                    contentDescription = stringResource(R.string.label_delete),
                    modifier = Modifier.scale(iconScale),
                    tint = MaterialTheme.colorScheme.onErrorContainer
                )
            }
        },
        content = {
            HistoryCard(item, sourceLanguage,  targetLanguage, onPlay, onClick)
        }
    )
}

@Composable
fun HistoryCard(
    item: TranslationHistoryItem,
    sourceLanguage: Language,
    targetLanguage: Language,
    onPlay: (text: String, language: Language) -> Unit,
    onClick: (TranslationHistoryItem) -> Unit
) {
    ElevatedCard(
        onClick = { onClick(item) },
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.elevatedCardColors(
            containerColor = MaterialTheme.colorScheme.surfaceContainerLow
        ),
        elevation = CardDefaults.elevatedCardElevation(defaultElevation = 0.5.dp),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // --- Top Row: Language Indicators & Time ---
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    LanguageBadge(text = sourceLanguage.name)
                    Icon(
                        imageVector = AppIcons.ArrowRight,
                        contentDescription = null,
                        modifier = Modifier
                            .size(14.dp)
                            .padding(horizontal = 4.dp),
                        tint = MaterialTheme.colorScheme.outline
                    )
                    LanguageBadge(text = targetLanguage.name)
                }

                Text(
                    text = item.getRelativeTimeSpan(),
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.outline
                )
            }

            Spacer(modifier = Modifier.size(12.dp))

            // --- Source Text (Subtle) ---
            Text(
                text = item.sourceText,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )

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

            // --- Translated Text (Prominent) ---
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.Top,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = item.text,
                    style = MaterialTheme.typography.titleMedium.copy(
                        fontSize = 18.sp,
                        fontWeight = FontWeight.SemiBold
                    ),
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier
                        .weight(1f)
                        .padding(end = 8.dp)
                )

                if (item.playable == true) {
                    IconButton(
                        onClick = { item.targetLanguageCode?.let { onPlay(item.text, targetLanguage) } },
                        modifier = Modifier
                            .size(32.dp)
                            .background(
                                MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
                                CircleShape
                            )
                    ) {
                        Icon(
                            imageVector = AppIcons.TextToSpeech,
                            contentDescription = stringResource(R.string.cd_play),
                            modifier = Modifier.size(16.dp),
                            tint = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun LanguageBadge(text: String) {
    Text(
        text = text,
        style = MaterialTheme.typography.labelSmall,
        fontWeight = FontWeight.Bold,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        modifier = Modifier
            .background(
                MaterialTheme.colorScheme.surfaceVariant,
                RoundedCornerShape(4.dp)
            )
            .padding(horizontal = 6.dp, vertical = 2.dp)
    )
}

// --- Preview ---

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
fun HistoryItemPreview() {
    val mockItem = TranslationHistoryItem(
        text = "Guten Morgen",
        sourceText = "Good Morning",
        sourceLanguageCode = 134,
        targetLanguageCode = 221,
        playable = true,
        timestamp = System.currentTimeMillis()
    )

    MaterialTheme {
        Column(Modifier.padding(16.dp)) {
            HistoryCard(
                item = mockItem, onClick = {},
                sourceLanguage = generateRandomLanguage(),
                targetLanguage = generateRandomLanguage(),
                onPlay = { _: String, _: Language -> },
            )
            Spacer(Modifier.size(16.dp))
            // Swipe visual mock
            Box(Modifier.background(MaterialTheme.colorScheme.errorContainer, RoundedCornerShape(16.dp))) {
                Row(Modifier
                    .fillMaxWidth()
                    .padding(16.dp), horizontalArrangement = Arrangement.End) {
                    Icon(AppIcons.Delete, null, tint = MaterialTheme.colorScheme.onErrorContainer)
                }
                HistoryCard(
                    item = mockItem.copy(text = "Example Swipe"),
                    onPlay = { _: String, _: Language -> },
                    onClick = {},
                    sourceLanguage = generateSimpleLanguage("German"),
                    targetLanguage = generateSimpleLanguage("English"),
                )
            }
        }
    }
}