@file:Suppress("HardCodedStringLiteral")
package eu.gaudian.translator.view

import androidx.compose.animation.AnimatedVisibility
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.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
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.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.StatusAction
import eu.gaudian.translator.utils.StatusMessageService
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedButton
import eu.gaudian.translator.view.composable.ComponentDefaults
import eu.gaudian.translator.view.settings.SettingsRoutes
import eu.gaudian.translator.viewmodel.MessageAction
import eu.gaudian.translator.viewmodel.MessageDisplayType
import eu.gaudian.translator.viewmodel.StatusState
import kotlinx.coroutines.launch

/**
 * A system for displaying status messages and loading indicators with a modern,
 * floating design consistent with the rest of the app's UI components.
 *
 * @param statusState The current state to display (e.g., Hidden, Loading, Message).
 * @param modifier The modifier to be applied to the component.
 * @param onDismiss Callback invoked when a message is dismissed.
 */
@Composable
fun StatusMessageSystem(
    statusState: StatusState,
    navController: NavController,
    modifier: Modifier = Modifier,
    onDismiss: () -> Unit = {}
) {
    AnimatedVisibility(
        visible = statusState != StatusState.Hidden,
        label = "StatusMessageSystemVisibility",
        enter = fadeIn(animationSpec = tween(150)),
        exit = fadeOut(animationSpec = tween(200)),
        modifier = modifier
    ) {
        when (statusState) {
            StatusState.Hidden -> { /* Do nothing, handled by AnimatedVisibility */
            }

            StatusState.Loading -> {
                FullScreenLoadingOverlay()
            }

            is StatusState.Message -> {
                // Position the message at the top of the screen
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp, bottom = 16.dp),
                    contentAlignment = Alignment.TopCenter
                ) {
                    StatusMessage(
                        message = statusState.text,
                        type = statusState.type,
                        action = statusState.action, // ADDED: Pass the action down.
                        navController = navController, // ADDED: Pass the NavController down.
                        onDismiss = onDismiss
                    )
                }
            }
        }
    }
}

/**
 * A full-screen loading indicator with a blurred background overlay.
 */
@Composable
fun FullScreenLoadingOverlay() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            // A semi-transparent background provides a modern scrim effect.
            .background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.6f))
            .clickable(enabled = false, onClick = {}), // Consume clicks
        contentAlignment = Alignment.Center
    ) {
        Surface(
            shape = RoundedCornerShape(24.dp),
            color = MaterialTheme.colorScheme.surfaceContainer,
            modifier = Modifier.shadow(elevation = 12.dp, shape = RoundedCornerShape(24.dp))
        ) {
            CircularProgressIndicator(
                modifier = Modifier
                    .size(64.dp)
                    .padding(12.dp),
                color = MaterialTheme.colorScheme.primary,
                strokeWidth = 4.dp
            )
        }
    }
}

/**
 * A floating status message card that appears at the top of the screen.
 */
@Composable
private fun StatusMessage(
    message: String,
    type: MessageDisplayType,
    action: MessageAction?,
    navController: NavController,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier
) {
    val coroutineScope = rememberCoroutineScope()


    AnimatedVisibility(
        visible = true, // Controlled by the parent's state
        enter = slideInVertically(initialOffsetY = { -it }) + fadeIn(),
        exit = slideOutVertically(targetOffsetY = { -it }) + fadeOut(),
        label = "StatusMessageAnimation"
    ) {
        Surface(
            modifier = modifier
                .fillMaxWidth(0.9f)
                .shadow(elevation = ComponentDefaults.DefaultElevation, shape = ComponentDefaults.DefaultShape)
                .clip(ComponentDefaults.DefaultShape),
            shape = ComponentDefaults.DefaultShape,
            color = MaterialTheme.colorScheme.surfaceContainer
        ) {
            Row(
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                when (type) {
                    MessageDisplayType.LOADING -> {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = MaterialTheme.colorScheme.primary,
                            strokeWidth = 2.dp
                        )
                    }
                    else -> {
                        val icon: ImageVector
                        val iconColor: Color
                        when (type) {
                            MessageDisplayType.SUCCESS -> {
                                icon = AppIcons.Check
                                iconColor = MaterialTheme.colorScheme.tertiary
                            }
                            MessageDisplayType.ERROR, MessageDisplayType.ACTIONABLE_ERROR -> {
                                icon = AppIcons.Error
                                iconColor = MaterialTheme.colorScheme.error
                            }
                            else -> {
                                icon = AppIcons.Info
                                iconColor = MaterialTheme.colorScheme.secondary
                            }
                        }
                        Icon(
                            imageVector = icon,
                            contentDescription = null,
                            tint = iconColor,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                }

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

                Text(
                    text = message,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.weight(1f)
                )

                if (action != null) {
                    AppOutlinedButton(
                        onClick = {
                            when (action) {
                                MessageAction.NAVIGATE_TO_API_KEYS -> {
                                    navController.navigate(SettingsRoutes.API_KEY)
                                }
                            }
                            coroutineScope.launch {
                            StatusMessageService.trigger(StatusAction.CancelPermanentMessage)
                            }
                        },
                        modifier = Modifier.padding(start = 8.dp)
                    ) {
                        Text(stringResource(R.string.title_settings))
                    }
                } else {
                    IconButton(
                        onClick = onDismiss,
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = AppIcons.Close,
                            contentDescription = stringResource(R.string.dismiss),
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}


// --- Previews (with a new one for Loading Message) ---

@ThemePreviews
@Composable
private fun StatusMessageSystemPreviewLoading() {
    Box(Modifier.fillMaxSize()) {
        StatusMessageSystem(statusState = StatusState.Loading, navController = NavController(context = LocalContext.current) )
    }
}

@ThemePreviews
@Composable
private fun StatusMessageSystemPreviewSuccess() {
    Box(Modifier.fillMaxSize()) {
        StatusMessageSystem(
            statusState = StatusState.Message(
                id = 1,
                text = "Operation completed successfully.",
                type = MessageDisplayType.SUCCESS
            ),
            navController = NavController(context = LocalContext.current) // Use a dummy NavController for preview
        )
    }
}

@ThemePreviews
@Composable
private fun StatusMessageSystemPreviewError() {
    Box(Modifier.fillMaxSize()) {
        StatusMessageSystem(
            statusState = StatusState.Message(
                id = 2,
                text = "An unknown error occurred.",
                type = MessageDisplayType.ERROR
            ),
            navController = NavController(context = LocalContext.current)
        )
    }
}

@ThemePreviews
@Composable
private fun StatusMessageSystemPreviewInfo() {
    Box(Modifier.fillMaxSize()) {
        StatusMessageSystem(
            statusState = StatusState.Message(
                id = 3,
                text = "This is just for your information.",
                type = MessageDisplayType.INFO
            ),
            navController = NavController(context = LocalContext.current)
        )
    }
}

// ADDED: Preview for the new loading message bar
@ThemePreviews
@Composable
private fun StatusMessageSystemPreviewLoadingMessage() {
    Box(Modifier.fillMaxSize()) {
        StatusMessageSystem(
            statusState = StatusState.Message(
                id = 4,
                text = "Processing in the background...",
                type = MessageDisplayType.LOADING
            ),
            navController = NavController(context = LocalContext.current)
        )
    }
}