package eu.gaudian.translator.view.dictionary

import android.content.ClipData
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.toClipEntry
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
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.ui.theme.semanticColors
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedButton
import eu.gaudian.translator.view.composable.AppSwitch
import eu.gaudian.translator.view.composable.DictionaryLanguageDropDown
import eu.gaudian.translator.view.composable.DropdownDefaults
import eu.gaudian.translator.view.composable.LargeDropdownMenuItem
import eu.gaudian.translator.viewmodel.CorrectionViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import kotlinx.coroutines.launch

// 1. STATEFUL COMPONENT (Connects to ViewModels)
@Composable
fun CorrectionScreen(
    correctionViewModel: CorrectionViewModel,
    languageViewModel: LanguageViewModel
) {
    val textFieldValue by correctionViewModel.textFieldValue.collectAsState()
    val explanation by correctionViewModel.explanation.collectAsState()
    val isLoading by correctionViewModel.isLoading.collectAsState()
    val correctedText by correctionViewModel.correctedText.collectAsState()
    val grammarOnly by correctionViewModel.grammarOnly.collectAsState()
    val selectedTone by correctionViewModel.tone.collectAsState()
    val errorMessage by correctionViewModel.error.collectAsState()

    val successColor = MaterialTheme.semanticColors.success

    CorrectionScreenContent(
        textFieldValue = textFieldValue,
        explanation = explanation,
        isLoading = isLoading,
        correctedText = correctedText,
        grammarOnly = grammarOnly,
        selectedTone = selectedTone,
        errorMessage = errorMessage,
        onInputTextChanged = correctionViewModel::onInputTextChanged,
        onClearText = correctionViewModel::clearText,
        onSetCorrectToneEnabled = correctionViewModel::setCorrectToneEnabled,
        onToneSelected = correctionViewModel::setTone,
        onCorrectClick = {
            languageViewModel.selectedDictionaryLanguage.value?.let { lang ->
                correctionViewModel.performCorrection(lang, successColor)
            }
        },
        languageDropdownContent = {
            DictionaryLanguageDropDown(
                languageViewModel = languageViewModel,
                modifier = Modifier.fillMaxWidth()
            )
        }
    )
}

// 2. STATELESS COMPONENT (Handles UI Layout)
@Composable
fun CorrectionScreenContent(
    textFieldValue: TextFieldValue,
    explanation: String?,
    isLoading: Boolean,
    correctedText: String?,
    grammarOnly: Boolean,
    selectedTone: CorrectionViewModel.Tone,
    errorMessage: String?,
    onInputTextChanged: (TextFieldValue) -> Unit,
    onClearText: () -> Unit,
    onSetCorrectToneEnabled: (Boolean) -> Unit,
    onToneSelected: (CorrectionViewModel.Tone) -> Unit,
    onCorrectClick: () -> Unit,
    languageDropdownContent: @Composable () -> Unit
) {
    val clipboard = LocalClipboard.current
    val clipboardManager = LocalClipboardManager.current
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val scrollState = rememberScrollState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // --- Editor Section ---
        Card(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(24.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(1.dp)
            )
        ) {
            // Box is used to overlay the buttons on top of the text field
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                contentAlignment = Alignment.BottomEnd
            ) {
                // Input Field
                OutlinedTextField(
                    value = textFieldValue,
                    onValueChange = onInputTextChanged,
                    shape = RoundedCornerShape(12.dp),
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 200.dp, max = 500.dp), // Height accommodates text + bottom buttons
                    enabled = !isLoading,
                    label = { Text(stringResource(R.string.text_enter_text_to_correct)) },
                    //placeholder = { Text("Type or paste text here...") }
                )

                // Action Buttons (Paste / Copy / Clear) - Floating inside the Box
                Row(
                    modifier = Modifier.padding(8.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    val textCopied = stringResource(R.string.text_copied_to_clipboard)

                    // 1. Paste Button (Visible only when text is empty)
                    val textClipBoardEmpty = stringResource(R.string.text_clipboard_empty)
                    AnimatedVisibility(
                        visible = textFieldValue.text.isEmpty(),
                        enter = fadeIn() + expandVertically(),
                        exit = fadeOut() + shrinkVertically()
                    ) {
                        IconButton(onClick = {
                            val clipboardText = clipboardManager.getText()?.text
                            if (!clipboardText.isNullOrBlank()) {
                                onInputTextChanged(TextFieldValue(clipboardText))
                            } else {
                                Toast.makeText(context, textClipBoardEmpty, Toast.LENGTH_SHORT).show()
                            }
                        }) {
                            Icon(
                                imageVector = Icons.Default.ContentPaste,
                                contentDescription = stringResource(R.string.label_paste),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // 2. Copy Button (Visible only when there is a result)
                    AnimatedVisibility(
                        visible = correctedText != null,
                        enter = fadeIn() + expandVertically(),
                        exit = fadeOut() + shrinkVertically()
                    ) {
                        correctedText?.let { textToCopy ->
                            IconButton(
                                onClick = {
                                    Toast.makeText(context, textCopied, Toast.LENGTH_SHORT).show()
                                    scope.launch {
                                        val clipData = ClipData.newPlainText(textToCopy, textToCopy)
                                        clipboard.setClipEntry(clipData.toClipEntry())
                                    }
                                },
                            ) {
                                Icon(
                                    imageVector = AppIcons.Copy,
                                    contentDescription = stringResource(R.string.text_copy_corrected_text),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }

                    // 3. Clear Button (Visible only when text is NOT empty)
                    AnimatedVisibility(visible = textFieldValue.text.isNotEmpty()) {
                        IconButton(onClick = onClearText) {
                            Icon(
                                imageVector = AppIcons.Clear,
                                contentDescription = stringResource(R.string.cd_clear_text),
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }

        // --- Settings Section ---
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
            )
        ) {
            Column(modifier = Modifier.padding(16.dp)) {


                // --- Action Bar ---
                Column {
                    if (errorMessage != null) {
                        Text(
                            text = errorMessage,
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodySmall,
                            modifier = Modifier.padding(bottom = 8.dp, start = 8.dp)
                        )
                    }

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        // Language Dropdown Slot
                        Box(modifier = Modifier.weight(1f)) {
                            languageDropdownContent()
                        }

                        // Correct Button
                        AppButton(
                            onClick = onCorrectClick,
                            enabled = textFieldValue.text.isNotBlank() && !isLoading,
                            modifier = Modifier.height(50.dp)
                        ) {
                            if (isLoading) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(20.dp),
                                    color = MaterialTheme.colorScheme.onPrimary,
                                    strokeWidth = 2.dp
                                )
                            } else {
                                Text(
                                    text = stringResource(R.string.label_action_correct),
                                    style = MaterialTheme.typography.labelLarge
                                )
                            }
                        }
                    }
                }

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






                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            imageVector = AppIcons.Settings, // Fallback icon
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text(
                                text = stringResource(R.string.correct_tone),
                                style = MaterialTheme.typography.titleSmall,
                                fontWeight = FontWeight.SemiBold
                            )
                            if (grammarOnly) {
                                Text(
                                    text = stringResource(R.string.label_grammar_only),
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }

                    AppSwitch(
                        checked = !grammarOnly,
                        onCheckedChange = onSetCorrectToneEnabled,
                        enabled = !isLoading
                    )
                }

                if (!grammarOnly) {
                    Spacer(modifier = Modifier.height(12.dp))
                    HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
                    Spacer(modifier = Modifier.height(12.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(R.string.label_target_tone),
                            style = MaterialTheme.typography.labelMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(end = 16.dp)
                        )
                        Box(modifier = Modifier.weight(1f)) {
                            ToneDropdown(
                                selectedTone = selectedTone,
                                onToneSelected = onToneSelected,
                                enabled = !isLoading
                            )
                        }
                    }
                }

            }
        }

        // --- Explanation / Results Section ---
        AnimatedVisibility(
            visible = explanation != null,
            enter = expandVertically() + fadeIn(),
            exit = shrinkVertically() + fadeOut()
        ) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.4f)
                )
            ) {
                Column(modifier = Modifier.padding(20.dp)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            imageVector = AppIcons.Info,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.tertiary,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = stringResource(R.string.text_explanation),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }

                    Spacer(modifier = Modifier.height(8.dp))

                    SelectionContainer {
                        Text(
                            text = explanation ?: "",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            lineHeight = 22.sp
                        )
                    }
                }
            }
        }


    }
}


@Composable
private fun ToneDropdown(
    selectedTone: CorrectionViewModel.Tone,
    onToneSelected: (CorrectionViewModel.Tone) -> Unit,
    enabled: Boolean
) {
    var expanded by remember { mutableStateOf(false) }

    Box(modifier = Modifier.fillMaxWidth()) {
        AppOutlinedButton(
            onClick = { if (enabled) expanded = true },
            enabled = enabled,
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = labelFor(selectedTone),
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium
                )
                Icon(
                    imageVector = if(expanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                    contentDescription = null,
                    modifier = Modifier.size(20.dp)
                )
            }
        }

        if (expanded) {
            val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)

            ModalBottomSheet(
                onDismissRequest = { expanded = false },
                sheetState = sheetState,
                containerColor = DropdownDefaults.containerColor()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .verticalScroll(rememberScrollState())
                        .padding(vertical = 8.dp) // Gives breathing room at top/bottom of list
                ) {
                    // Replaced with LargeDropdownMenuItem
                    LargeDropdownMenuItem(
                        text = stringResource(R.string.text_none),
                        selected = selectedTone == CorrectionViewModel.Tone.NONE,
                        enabled = enabled,
                        onClick = {
                            onToneSelected(CorrectionViewModel.Tone.NONE)
                            expanded = false
                        }
                    )

                    HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))

                    val options = listOf(
                        CorrectionViewModel.Tone.FORMAL,
                        CorrectionViewModel.Tone.CASUAL,
                        CorrectionViewModel.Tone.COLLOQUIAL,
                        CorrectionViewModel.Tone.POLITE,
                        CorrectionViewModel.Tone.PROFESSIONAL,
                        CorrectionViewModel.Tone.FRIENDLY,
                        CorrectionViewModel.Tone.ACADEMIC,
                        CorrectionViewModel.Tone.CREATIVE
                    )

                    options.forEach { tone ->
                        // Replaced with LargeDropdownMenuItem
                        LargeDropdownMenuItem(
                            text = labelFor(tone),
                            selected = selectedTone == tone,
                            enabled = enabled,
                            onClick = {
                                onToneSelected(tone)
                                expanded = false
                            }
                        )
                    }

                    Spacer(modifier = Modifier.navigationBarsPadding().height(16.dp))
                }
            }
        }
    }
}

@Composable
fun labelFor(tone: CorrectionViewModel.Tone): String = when (tone) {
    CorrectionViewModel.Tone.NONE -> stringResource(R.string.text_none)
    CorrectionViewModel.Tone.FORMAL -> stringResource(R.string.formal)
    CorrectionViewModel.Tone.CASUAL -> stringResource(R.string.label_casual)
    CorrectionViewModel.Tone.COLLOQUIAL -> stringResource(R.string.label_colloquial)
    CorrectionViewModel.Tone.POLITE -> stringResource(R.string.polite)
    CorrectionViewModel.Tone.PROFESSIONAL -> stringResource(R.string.professional)
    CorrectionViewModel.Tone.FRIENDLY -> stringResource(R.string.friendly)
    CorrectionViewModel.Tone.ACADEMIC -> stringResource(R.string.label_academic)
    CorrectionViewModel.Tone.CREATIVE -> stringResource(R.string.creative)
}

// --- PREVIEWS ---

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "1. Empty State")
@Composable
private fun CorrectionScreenPreview() {
    MaterialTheme {
        CorrectionScreenContent(
            textFieldValue = TextFieldValue(""),
            explanation = null,
            isLoading = false,
            correctedText = null,
            grammarOnly = true,
            selectedTone = CorrectionViewModel.Tone.NONE,
            errorMessage = null,
            onInputTextChanged = {},
            onClearText = {},
            onSetCorrectToneEnabled = {},
            onToneSelected = {},
            onCorrectClick = {},
            languageDropdownContent = {
                AppOutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth()) {
                    Text("German")
                }
            }
        )
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "2. Results State")
@Composable
private fun CorrectionScreenResultsPreview() {
    MaterialTheme {
        CorrectionScreenContent(
            textFieldValue = TextFieldValue("In diesen Satz ist ein Fehler"),
            explanation = "Korrektur der Deklination von 'dieser' (Dativ Singular Maskulinum: 'diesem' statt 'diesen') und Ergänzung des fehlenden Schlusszeichens.",
            isLoading = false,
            correctedText = "In diesem Satz ist ein Fehler.",
            grammarOnly = false,
            selectedTone = CorrectionViewModel.Tone.PROFESSIONAL,
            errorMessage = null,
            onInputTextChanged = {},
            onClearText = {},
            onSetCorrectToneEnabled = {},
            onToneSelected = {},
            onCorrectClick = {},
            languageDropdownContent = {
                AppOutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth()) {
                    Text("German")
                }
            }
        )
    }
}