package com.swoosh.microblog.ui.settings

import android.content.Intent
import android.net.Uri
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.BrightnessAuto
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Tag
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.swoosh.microblog.data.AccountManager
import com.swoosh.microblog.data.toDisplayUrl
import com.swoosh.microblog.data.TagsPreferences
import com.swoosh.microblog.data.SiteMetadataCache
import com.swoosh.microblog.data.api.ApiClient
import com.swoosh.microblog.data.model.GhostAccount
import com.swoosh.microblog.ui.animation.SwooshMotion
import com.swoosh.microblog.ui.components.ConfirmationDialog
import com.swoosh.microblog.ui.feed.AccountAvatar
import com.swoosh.microblog.ui.theme.ThemeMode
import com.swoosh.microblog.ui.theme.ThemeViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onBack: () -> Unit,
    onLogout: () -> Unit,
    themeViewModel: ThemeViewModel? = null,
    onNavigateToPages: () -> Unit = {},
    onNavigateToTags: () -> Unit = {}
) {
    val context = LocalContext.current
    val accountManager = remember { AccountManager(context) }
    val activeAccount = remember { accountManager.getActiveAccount() }
    val siteMetadataCache = remember { SiteMetadataCache(context) }
    val siteData = remember { activeAccount?.let { siteMetadataCache.get(it.id) } }

    val currentThemeMode = themeViewModel?.themeMode?.collectAsStateWithLifecycle()

    var showDisconnectDialog by remember { mutableStateOf(false) }
    var showDisconnectAllDialog by remember { mutableStateOf(false) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Settings") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp)
                .verticalScroll(rememberScrollState())
        ) {
            // --- Appearance section ---
            if (themeViewModel != null) {
                Text("Appearance", style = MaterialTheme.typography.titleMedium)
                Spacer(modifier = Modifier.height(12.dp))

                ThemeModeSelector(
                    currentMode = currentThemeMode?.value ?: ThemeMode.SYSTEM,
                    onModeSelected = { themeViewModel.setThemeMode(it) }
                )

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

            // --- Blog Info section ---
            if (siteData != null) {
                Text("Blog", style = MaterialTheme.typography.titleMedium)
                Spacer(modifier = Modifier.height(12.dp))

                Card(modifier = Modifier.fillMaxWidth()) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            // Site logo/icon or fallback initial
                            val siteImageUrl = siteData.logo ?: siteData.icon
                            if (siteImageUrl != null) {
                                AsyncImage(
                                    model = siteImageUrl,
                                    contentDescription = "Site icon",
                                    modifier = Modifier
                                        .size(48.dp)
                                        .clip(CircleShape),
                                    contentScale = ContentScale.Crop
                                )
                            } else {
                                val initial = siteData.title?.firstOrNull()?.uppercase() ?: "?"
                                val color = activeAccount?.let {
                                    Color(GhostAccount.colorForIndex(it.colorIndex))
                                } ?: MaterialTheme.colorScheme.primary
                                Box(
                                    modifier = Modifier
                                        .size(48.dp)
                                        .clip(CircleShape)
                                        .background(color),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = initial,
                                        color = Color.White,
                                        style = MaterialTheme.typography.titleMedium
                                    )
                                }
                            }

                            Column(modifier = Modifier.weight(1f)) {
                                Text(
                                    text = siteData.title ?: "Ghost Blog",
                                    style = MaterialTheme.typography.titleMedium
                                )
                                if (!siteData.description.isNullOrBlank()) {
                                    Text(
                                        text = siteData.description!!,
                                        style = MaterialTheme.typography.bodySmall,
                                        fontStyle = FontStyle.Italic,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }

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

                        // URL
                        val siteUrl = siteData.url
                        if (!siteUrl.isNullOrBlank()) {
                            Text(
                                text = siteUrl.toDisplayUrl(),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }

                        // Version + locale
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            if (siteData.version != null) {
                                Text(
                                    text = "Ghost ${siteData.version}",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            if (siteData.locale != null) {
                                Text(
                                    text = "Locale: ${siteData.locale}",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }

                // Version warning
                val majorVersion = siteData.version?.split(".")?.firstOrNull()?.toIntOrNull()
                if (majorVersion != null && majorVersion < 5) {
                    Spacer(modifier = Modifier.height(8.dp))
                    ElevatedCard(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.elevatedCardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(12.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.Warning,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error,
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Ghost ${siteData.version} is older than v5. Some features may not work.",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                        }
                    }
                }

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

                // Open Ghost Admin button
                val ghostAdminUrl = remember(activeAccount) {
                    activeAccount?.blogUrl?.trimEnd('/') + "/ghost/"
                }
                OutlinedButton(
                    onClick = {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(ghostAdminUrl))
                        context.startActivity(intent)
                    },
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Icon(
                        Icons.AutoMirrored.Filled.OpenInNew,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Open Ghost Admin")
                }

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

            // --- Features section ---
            Text("Features", style = MaterialTheme.typography.titleMedium)
            Spacer(modifier = Modifier.height(12.dp))

            TagsSettingsSection(onNavigateToTags = onNavigateToTags)

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

            // --- Current Account section ---
            Text("Current Account", style = MaterialTheme.typography.titleMedium)
            Spacer(modifier = Modifier.height(12.dp))

            var cardVisible by remember { mutableStateOf(false) }
            LaunchedEffect(Unit) { cardVisible = true }

            AnimatedVisibility(
                visible = cardVisible && activeAccount != null,
                enter = fadeIn(SwooshMotion.quick()) + scaleIn(initialScale = 0.95f, animationSpec = SwooshMotion.quick())
            ) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        AccountAvatar(account = activeAccount!!, size = 40)
                        Column {
                            Text(
                                text = activeAccount.name,
                                style = MaterialTheme.typography.bodyLarge
                            )
                            Text(
                                text = activeAccount.blogUrl.toDisplayUrl(),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }

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

            // Account count info
            val accountCount = accountManager.getAccounts().size
            Text(
                text = "$accountCount of ${AccountManager.MAX_ACCOUNTS} accounts",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            // Static Pages
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable(onClick = onNavigateToPages)
                    .padding(vertical = 12.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Static Pages",
                    style = MaterialTheme.typography.bodyLarge
                )
                Text(
                    text = "\u203A",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

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

            // Disconnect current account
            OutlinedButton(
                onClick = { showDisconnectDialog = true },
                modifier = Modifier.fillMaxWidth(),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.error
                )
            ) {
                Text("Disconnect Current Account")
            }

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

            // App version
            Spacer(modifier = Modifier.height(16.dp))
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            Text(
                text = "Swoosh v${packageInfo.versionName}",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.fillMaxWidth(),
                textAlign = androidx.compose.ui.text.style.TextAlign.Center
            )

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

            // Disconnect all
            if (accountManager.getAccounts().size > 1) {
                TextButton(
                    onClick = { showDisconnectAllDialog = true },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("Disconnect All Accounts")
                }
            }
        }
    }

    if (showDisconnectDialog) {
        ConfirmationDialog(
            title = "Disconnect Account?",
            message = "Remove \"${activeAccount?.name ?: ""}\"? You'll need to set up again.",
            confirmLabel = "Disconnect",
            onConfirm = {
                showDisconnectDialog = false
                activeAccount?.let { account ->
                    accountManager.removeAccount(account.id)
                    ApiClient.reset()
                    if (accountManager.getAccounts().isEmpty()) onLogout() else onBack()
                }
            },
            onDismiss = { showDisconnectDialog = false }
        )
    }

    if (showDisconnectAllDialog) {
        ConfirmationDialog(
            title = "Disconnect All?",
            message = "Remove all accounts? You'll need to set up from scratch.",
            confirmLabel = "Disconnect All",
            onConfirm = {
                showDisconnectAllDialog = false
                accountManager.clearAll()
                ApiClient.reset()
                onLogout()
            },
            onDismiss = { showDisconnectAllDialog = false }
        )
    }
}

@Composable
fun TagsSettingsSection(onNavigateToTags: () -> Unit = {}) {
    val context = LocalContext.current
    val tagsPreferences = remember { TagsPreferences(context) }
    var tagsEnabled by remember { mutableStateOf(tagsPreferences.isTagsEnabled()) }

    Card(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "Enable tags",
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
                Switch(
                    checked = tagsEnabled,
                    onCheckedChange = { enabled ->
                        tagsEnabled = enabled
                        tagsPreferences.setTagsEnabled(enabled)
                    }
                )
            }

            Text(
                text = "Show tag management and tag filters in feed",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

            // Manage tags navigation
            AnimatedVisibility(
                visible = tagsEnabled,
                enter = fadeIn(SwooshMotion.quick()) + expandVertically(animationSpec = SwooshMotion.snappy()),
                exit = fadeOut(SwooshMotion.quick()) + shrinkVertically(animationSpec = SwooshMotion.snappy())
            ) {
                OutlinedButton(
                    onClick = onNavigateToTags,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 12.dp)
                ) {
                    Icon(
                        Icons.Default.Tag,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Manage Tags")
                }
            }
        }
    }
}

@Composable
fun ThemeModeSelector(
    currentMode: ThemeMode,
    onModeSelected: (ThemeMode) -> Unit
) {
    val modes = listOf(
        Triple(ThemeMode.SYSTEM, "System", Icons.Default.BrightnessAuto),
        Triple(ThemeMode.LIGHT, "Light", Icons.Default.LightMode),
        Triple(ThemeMode.DARK, "Dark", Icons.Default.DarkMode)
    )

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        modes.forEach { (mode, label, icon) ->
            val selected = currentMode == mode
            FilterChip(
                selected = selected,
                onClick = { onModeSelected(mode) },
                label = { Text(label) },
                leadingIcon = {
                    Icon(
                        imageVector = icon,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                },
                modifier = Modifier.weight(1f)
            )
        }
    }
}
