package com.swoosh.microblog.ui.setup

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetupScreen(
    onSetupComplete: () -> Unit,
    onBack: (() -> Unit)? = null,
    viewModel: SetupViewModel = viewModel()
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    val uriHandler = LocalUriHandler.current

    LaunchedEffect(state.isSuccess) {
        if (state.isSuccess) onSetupComplete()
    }

    val primaryColor = MaterialTheme.colorScheme.primary
    val tertiaryColor = MaterialTheme.colorScheme.tertiary
    val secondaryColor = MaterialTheme.colorScheme.secondary

    // Determine if the URL looks valid enough to show the hint
    val urlLooksValid = remember(state.url) {
        val trimmed = state.url.trim()
        trimmed.isNotEmpty() && (
            trimmed.startsWith("http://") ||
            trimmed.startsWith("https://") ||
            trimmed.contains(".")
        )
    }

    // Build the normalized integrations URL from the user's input
    val integrationsUrl = remember(state.url) {
        val trimmed = state.url.trim().trimEnd('/')
        val withScheme = if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
            trimmed
        } else {
            "https://$trimmed"
        }
        "$withScheme/ghost/#/settings/integrations"
    }

    Scaffold(
        topBar = {
            if (state.isAddingAccount && onBack != null) {
                TopAppBar(
                    title = { Text("Add Account") },
                    navigationIcon = {
                        IconButton(onClick = onBack) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back")
                        }
                    }
                )
            }
        }
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
        ) {
            // Full-screen animated background behind all UI
            PulsingCirclesBackground(
                primaryColor = primaryColor,
                tertiaryColor = tertiaryColor,
                secondaryColor = secondaryColor,
                modifier = Modifier.fillMaxSize()
            )

            // Content layered on top
            if (state.showConfirmation) {
                // Confirmation card
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    AnimatedVisibility(
                        visible = true,
                        enter = fadeIn() + scaleIn(initialScale = 0.9f)
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(24.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Card(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(24.dp),
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    // Site icon
                                    if (state.siteIcon != null) {
                                        AsyncImage(
                                            model = state.siteIcon,
                                            contentDescription = "Site icon",
                                            modifier = Modifier
                                                .size(64.dp)
                                                .clip(CircleShape),
                                            contentScale = ContentScale.Crop
                                        )
                                        Spacer(modifier = Modifier.height(16.dp))
                                    }

                                    // Site title
                                    Text(
                                        text = state.siteName ?: "Ghost Blog",
                                        style = MaterialTheme.typography.titleLarge
                                    )

                                    // Site description
                                    if (!state.siteDescription.isNullOrBlank()) {
                                        Spacer(modifier = Modifier.height(8.dp))
                                        Text(
                                            text = state.siteDescription!!,
                                            style = MaterialTheme.typography.bodyMedium,
                                            fontStyle = FontStyle.Italic,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }

                                    // Ghost version
                                    if (state.siteVersion != null) {
                                        Spacer(modifier = Modifier.height(8.dp))
                                        Text(
                                            text = "Ghost ${state.siteVersion}",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }

                            // Version warning
                            if (state.versionWarning) {
                                Spacer(modifier = Modifier.height(12.dp))
                                ElevatedCard(
                                    modifier = Modifier.fillMaxWidth(),
                                    colors = CardDefaults.elevatedCardColors(
                                        containerColor = MaterialTheme.colorScheme.errorContainer
                                    )
                                ) {
                                    Row(
                                        modifier = Modifier.padding(16.dp),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(
                                            Icons.Default.Warning,
                                            contentDescription = null,
                                            tint = MaterialTheme.colorScheme.error,
                                            modifier = Modifier.size(20.dp)
                                        )
                                        Spacer(modifier = Modifier.width(12.dp))
                                        Text(
                                            text = "Ghost version ${state.siteVersion} is older than v5. Some features may not work correctly.",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onErrorContainer
                                        )
                                    }
                                }
                            }

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

                            // Buttons
                            Button(
                                onClick = viewModel::confirmConnection,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text("Tak, po\u0142\u0105cz")
                            }

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

                            OutlinedButton(
                                onClick = viewModel::cancelConfirmation,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text("Wstecz")
                            }
                        }
                    }
                }
            } else {
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // Top area with branding
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = if (state.isAddingAccount) "Add Account" else "Swoosh",
                            style = MaterialTheme.typography.headlineLarge,
                            color = MaterialTheme.colorScheme.primary
                        )

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

                        Text(
                            text = if (state.isAddingAccount) "Connect another Ghost instance"
                                   else "Connect to your Ghost instance",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                // Bottom area with inputs and button
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                        .padding(bottom = 32.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                // Account name field
                OutlinedTextField(
                    value = state.accountName,
                    onValueChange = viewModel::updateAccountName,
                    label = { Text("Account Name (optional)") },
                    placeholder = { Text("e.g., Personal Blog") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )

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

                OutlinedTextField(
                    value = state.url,
                    onValueChange = viewModel::updateUrl,
                    label = { Text("Ghost Instance URL") },
                    placeholder = { Text("https://your-blog.ghost.io") },
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
                    modifier = Modifier.fillMaxWidth()
                )

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

                OutlinedTextField(
                    value = state.apiKey,
                    onValueChange = viewModel::updateApiKey,
                    label = { Text("Admin API Key") },
                    placeholder = { Text("key_id:secret") },
                    singleLine = true,
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth()
                )

                // API key hint with link to Ghost integrations page
                AnimatedVisibility(
                    visible = urlLooksValid,
                    enter = fadeIn(),
                    exit = fadeOut()
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 6.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Outlined.Info,
                            contentDescription = null,
                            modifier = Modifier.size(14.dp),
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )

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

                        val linkColor = MaterialTheme.colorScheme.primary
                        val annotatedText = buildAnnotatedString {
                            withStyle(
                                SpanStyle(color = MaterialTheme.colorScheme.onSurfaceVariant)
                            ) {
                                append("Find your API key at ")
                            }
                            pushStringAnnotation(tag = "URL", annotation = integrationsUrl)
                            withStyle(
                                SpanStyle(
                                    color = linkColor,
                                    textDecoration = TextDecoration.Underline
                                )
                            ) {
                                append("Settings \u2192 Integrations")
                            }
                            pop()
                        }

                        Text(
                            text = annotatedText,
                            style = MaterialTheme.typography.bodySmall,
                            modifier = Modifier.clickable {
                                uriHandler.openUri(integrationsUrl)
                            }
                        )
                    }
                }

                if (state.error != null) {
                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = state.error!!,
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall
                    )
                }

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

                Button(
                    onClick = viewModel::save,
                    enabled = !state.isTesting,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    if (state.isTesting) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("Testing connection...")
                    } else {
                        Text(if (state.isAddingAccount) "Add Account" else "Connect")
                    }
                }
            }
            }
            }
        }
    }
}

@Composable
private fun PulsingCirclesBackground(
    primaryColor: Color,
    tertiaryColor: Color,
    secondaryColor: Color,
    modifier: Modifier = Modifier
) {
    val infiniteTransition = rememberInfiniteTransition(label = "pulse")

    val scale1 by infiniteTransition.animateFloat(
        initialValue = 0.6f, targetValue = 1.4f,
        animationSpec = infiniteRepeatable(
            animation = tween(4000, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "scale1"
    )
    val alpha1 by infiniteTransition.animateFloat(
        initialValue = 0.25f, targetValue = 0.55f,
        animationSpec = infiniteRepeatable(
            animation = tween(4000, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "alpha1"
    )

    val scale2 by infiniteTransition.animateFloat(
        initialValue = 1.3f, targetValue = 0.5f,
        animationSpec = infiniteRepeatable(
            animation = tween(5500, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "scale2"
    )
    val alpha2 by infiniteTransition.animateFloat(
        initialValue = 0.20f, targetValue = 0.50f,
        animationSpec = infiniteRepeatable(
            animation = tween(5500, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "alpha2"
    )

    val scale3 by infiniteTransition.animateFloat(
        initialValue = 0.7f, targetValue = 1.5f,
        animationSpec = infiniteRepeatable(
            animation = tween(6500, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "scale3"
    )
    val alpha3 by infiniteTransition.animateFloat(
        initialValue = 0.18f, targetValue = 0.45f,
        animationSpec = infiniteRepeatable(
            animation = tween(6500, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ), label = "alpha3"
    )

    Canvas(
        modifier = modifier.blur(40.dp)
    ) {
        val w = size.width
        val h = size.height

        // Circle 1 -- primary, upper-left
        val radius1 = w * 0.50f * scale1
        drawCircle(
            brush = Brush.radialGradient(
                colors = listOf(primaryColor.copy(alpha = alpha1), Color.Transparent),
                center = Offset(w * 0.3f, h * 0.35f),
                radius = radius1
            ),
            radius = radius1,
            center = Offset(w * 0.3f, h * 0.35f)
        )

        // Circle 2 -- tertiary, right
        val radius2 = w * 0.55f * scale2
        drawCircle(
            brush = Brush.radialGradient(
                colors = listOf(tertiaryColor.copy(alpha = alpha2), Color.Transparent),
                center = Offset(w * 0.75f, h * 0.45f),
                radius = radius2
            ),
            radius = radius2,
            center = Offset(w * 0.75f, h * 0.45f)
        )

        // Circle 3 -- secondary, bottom-center
        val radius3 = w * 0.45f * scale3
        drawCircle(
            brush = Brush.radialGradient(
                colors = listOf(secondaryColor.copy(alpha = alpha3), Color.Transparent),
                center = Offset(w * 0.5f, h * 0.7f),
                radius = radius3
            ),
            radius = radius3,
            center = Offset(w * 0.5f, h * 0.7f)
        )
    }
}
