package com.fabledsword.minstrel.update.ui

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.TriangleAlert
import com.fabledsword.minstrel.update.data.VersionResult

/**
 * Shell-level banner shown when the server reports `min_client_version`
 * newer than our build. Non-blocking — locally cached content keeps
 * working; the banner is the nudge to install the next APK. "Check
 * now" forces a fresh /healthz probe.
 */
@Composable
fun VersionTooOldBanner(viewModel: VersionTooOldViewModel = hiltViewModel()) {
    val result by viewModel.result.collectAsStateWithLifecycle()
    AnimatedVisibility(
        visible = result == VersionResult.TOO_OLD,
        enter = expandVertically() + fadeIn(),
        exit = shrinkVertically() + fadeOut(),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.errorContainer)
                .padding(horizontal = 16.dp, vertical = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Icon(
                imageVector = Lucide.TriangleAlert,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onErrorContainer,
            )
            Text(
                text = "This app is older than the server requires. " +
                    "Cached content still works; install an update when ready.",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onErrorContainer,
                modifier = Modifier.weight(1f),
            )
            TextButton(onClick = { viewModel.recheck() }) {
                Text(
                    text = "Check now",
                    color = MaterialTheme.colorScheme.onErrorContainer,
                )
            }
        }
    }
}
