package com.swoosh.microblog.ui.newsletter

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.People
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.swoosh.microblog.data.NewsletterPreferences
import com.swoosh.microblog.data.repository.PostRepository
import com.swoosh.microblog.data.model.GhostNewsletter
import com.swoosh.microblog.ui.animation.SwooshMotion

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewsletterScreen() {
    val context = LocalContext.current
    val newsletterPreferences = remember { NewsletterPreferences(context) }
    var newsletterEnabled by remember { mutableStateOf(newsletterPreferences.isNewsletterEnabled()) }
    var validationStatus by remember { mutableStateOf<String?>(null) }
    var newsletters by remember { mutableStateOf<List<GhostNewsletter>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var subscriberCount by remember { mutableStateOf<Int?>(null) }

    // Load newsletters on launch if enabled
    LaunchedEffect(newsletterEnabled) {
        if (newsletterEnabled) {
            isLoading = true
            try {
                val repository = PostRepository(context)
                val result = repository.fetchNewsletters()
                result.fold(
                    onSuccess = {
                        newsletters = it
                        validationStatus = "${it.size} newsletter(s) found"
                    },
                    onFailure = {
                        validationStatus = "Could not load newsletters"
                    }
                )
                // Fetch subscriber count
                val membersResult = repository.fetchSubscriberCount()
                membersResult.fold(
                    onSuccess = { subscriberCount = it },
                    onFailure = { /* ignore */ }
                )
            } catch (_: Exception) {
                validationStatus = "Could not load newsletters"
            }
            isLoading = false
        } else {
            newsletters = emptyList()
            validationStatus = null
            subscriberCount = null
        }
    }

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("Newsletter") }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp)
                .verticalScroll(rememberScrollState())
        ) {
            // Enable/Disable toggle
            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 newsletter features",
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                        Switch(
                            checked = newsletterEnabled,
                            onCheckedChange = { enabled ->
                                newsletterEnabled = enabled
                                newsletterPreferences.setNewsletterEnabled(enabled)
                            }
                        )
                    }

                    Text(
                        text = "Show newsletter sending options when publishing posts",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            // Newsletter details (when enabled)
            AnimatedVisibility(
                visible = newsletterEnabled,
                enter = fadeIn(SwooshMotion.quick()) + expandVertically(animationSpec = SwooshMotion.snappy()),
                exit = fadeOut(SwooshMotion.quick()) + shrinkVertically(animationSpec = SwooshMotion.snappy())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))

                    if (isLoading) {
                        Card(modifier = Modifier.fillMaxWidth()) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(32.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator()
                            }
                        }
                    } else {
                        // Subscriber count card
                        if (subscriberCount != null) {
                            Card(modifier = Modifier.fillMaxWidth()) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(16.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                                ) {
                                    Icon(
                                        Icons.Default.People,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.primary
                                    )
                                    Column {
                                        Text(
                                            text = "$subscriberCount",
                                            style = MaterialTheme.typography.headlineMedium,
                                            fontWeight = FontWeight.Bold
                                        )
                                        Text(
                                            text = "Subscribers",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }
                            Spacer(modifier = Modifier.height(12.dp))
                        }

                        // Newsletters list
                        if (newsletters.isNotEmpty()) {
                            Text(
                                "Your Newsletters",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )

                            newsletters.forEach { newsletter ->
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(bottom = 8.dp)
                                ) {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                                    ) {
                                        Icon(
                                            Icons.Default.Email,
                                            contentDescription = null,
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                        Column(modifier = Modifier.weight(1f)) {
                                            Text(
                                                text = newsletter.name,
                                                style = MaterialTheme.typography.bodyLarge,
                                                fontWeight = FontWeight.Medium
                                            )
                                            if (!newsletter.description.isNullOrBlank()) {
                                                Text(
                                                    text = newsletter.description,
                                                    style = MaterialTheme.typography.bodySmall,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                            Row(
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                Text(
                                                    text = "Status: ${newsletter.status}",
                                                    style = MaterialTheme.typography.labelSmall,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                                Text(
                                                    text = "Visibility: ${newsletter.visibility}",
                                                    style = MaterialTheme.typography.labelSmall,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (validationStatus != null) {
                            Card(modifier = Modifier.fillMaxWidth()) {
                                Text(
                                    text = validationStatus!!,
                                    style = MaterialTheme.typography.bodyMedium,
                                    modifier = Modifier.padding(16.dp)
                                )
                            }
                        }
                    }

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

                    // Info card
                    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Text(
                                text = "How it works",
                                style = MaterialTheme.typography.titleSmall,
                                fontWeight = FontWeight.SemiBold
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "When enabled, the publish dialog offers options to send posts as newsletters or email-only content to your subscribers.",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }

            // Disabled state info
            AnimatedVisibility(
                visible = !newsletterEnabled,
                enter = fadeIn(SwooshMotion.quick()) + expandVertically(animationSpec = SwooshMotion.snappy()),
                exit = fadeOut(SwooshMotion.quick()) + shrinkVertically(animationSpec = SwooshMotion.snappy())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))
                    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Icon(
                                Icons.Default.Email,
                                contentDescription = null,
                                modifier = Modifier.size(48.dp),
                                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                            )
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = "Newsletter features are disabled",
                                style = MaterialTheme.typography.bodyLarge,
                                textAlign = TextAlign.Center
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "Enable to send posts as newsletters to your subscribers",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }
            }
        }
    }
}
