package com.swoosh.microblog.ui.detail

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
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.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material.icons.automirrored.filled.Article
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.TextFields
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.outlined.PushPin
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.swoosh.microblog.data.CredentialsManager
import com.swoosh.microblog.data.PreviewHtmlBuilder
import com.swoosh.microblog.data.ShareUtils
import com.swoosh.microblog.data.model.FeedPost
import com.swoosh.microblog.data.model.LinkPreview
import com.swoosh.microblog.data.model.PostStats
import com.swoosh.microblog.data.model.QueueStatus
import com.swoosh.microblog.ui.animation.SwooshMotion
import com.swoosh.microblog.ui.components.AudioPlayer
import com.swoosh.microblog.ui.components.ConfirmationDialog
import com.swoosh.microblog.ui.components.VideoPlayer
import com.swoosh.microblog.ui.feed.FileAttachmentCard
import com.swoosh.microblog.ui.feed.FullScreenGallery
import com.swoosh.microblog.ui.feed.StatusBadge
import com.swoosh.microblog.ui.feed.formatRelativeTime
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun DetailScreen(
    post: FeedPost,
    onBack: () -> Unit,
    onEdit: (FeedPost) -> Unit,
    onDelete: (FeedPost) -> Unit,
    onPreview: ((String) -> Unit)? = null,
    onTogglePin: (FeedPost) -> Unit = {}
) {
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showOverflowMenu by remember { mutableStateOf(false) }
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    val coroutineScope = rememberCoroutineScope()
    val baseUrl = remember { CredentialsManager(context).ghostUrl }

    val isPublished = post.status == "published" && post.queueStatus == QueueStatus.NONE
    val postUrl = remember(post, baseUrl) { ShareUtils.resolvePostUrl(post, baseUrl) }
    val canShare = isPublished && postUrl != null

    var showGallery by remember { mutableStateOf(false) }
    var galleryStartIndex by remember { mutableIntStateOf(0) }

    // Determine images to show
    val allImages = if (post.imageUrls.isNotEmpty()) {
        post.imageUrls
    } else if (post.imageUrl != null) {
        listOf(post.imageUrl)
    } else {
        emptyList()
    }

    // D1: Content reveal sequence
    val revealCount = 8 // status, text, tags, gallery, video, audio, link, stats
    val sectionVisible = remember { List(revealCount) { mutableStateOf(false) } }
    LaunchedEffect(Unit) {
        sectionVisible.forEachIndexed { index, state ->
            delay(SwooshMotion.RevealDelayMs * index)
            state.value = true
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Post") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back")
                    }
                },
                actions = {
                    // Pin/Unpin button
                    IconButton(onClick = { onTogglePin(post) }) {
                        Icon(
                            imageVector = if (post.featured) Icons.Filled.PushPin else Icons.Outlined.PushPin,
                            contentDescription = if (post.featured) "Unpin" else "Pin",
                            tint = if (post.featured) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    // Preview button - show rendered HTML
                    IconButton(onClick = {
                        val html = if (!post.htmlContent.isNullOrBlank()) {
                            PreviewHtmlBuilder.wrapExistingHtml(post.htmlContent)
                        } else {
                            val linkPreview = if (post.linkUrl != null) {
                                LinkPreview(
                                    url = post.linkUrl,
                                    title = post.linkTitle,
                                    description = post.linkDescription,
                                    imageUrl = post.linkImageUrl
                                )
                            } else null
                            PreviewHtmlBuilder.build(
                                text = post.textContent,
                                imageUrl = post.imageUrl,
                                linkPreview = linkPreview
                            )
                        }
                        onPreview?.invoke(html)
                    }) {
                        Icon(Icons.Default.Visibility, "View preview")
                    }
                    // Share button - only for published posts with a URL
                    if (canShare) {
                        IconButton(onClick = {
                            val shareText = ShareUtils.formatShareContent(post, postUrl!!)
                            val sendIntent = Intent(Intent.ACTION_SEND).apply {
                                type = "text/plain"
                                putExtra(Intent.EXTRA_TEXT, shareText)
                            }
                            context.startActivity(Intent.createChooser(sendIntent, "Share post"))
                        }) {
                            Icon(Icons.Default.Share, "Share")
                        }
                    }
                    IconButton(onClick = { onEdit(post) }) {
                        Icon(Icons.Default.Edit, "Edit")
                    }
                    // Overflow menu with Copy link and Delete
                    Box {
                        IconButton(onClick = { showOverflowMenu = true }) {
                            Icon(Icons.Default.MoreVert, "More options")
                        }
                        DropdownMenu(
                            expanded = showOverflowMenu,
                            onDismissRequest = { showOverflowMenu = false }
                        ) {
                            if (canShare) {
                                DropdownMenuItem(
                                    text = { Text("Copy link") },
                                    onClick = {
                                        showOverflowMenu = false
                                        val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                        clipboard.setPrimaryClip(ClipData.newPlainText("Post URL", postUrl))
                                        coroutineScope.launch {
                                            snackbarHostState.showSnackbar("Link copied to clipboard")
                                        }
                                    },
                                    leadingIcon = {
                                        Icon(Icons.Default.ContentCopy, contentDescription = null)
                                    }
                                )
                            }
                            DropdownMenuItem(
                                text = { Text("Delete") },
                                onClick = {
                                    showOverflowMenu = false
                                    showDeleteDialog = true
                                },
                                leadingIcon = {
                                    Icon(
                                        Icons.Default.Delete,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.error
                                    )
                                }
                            )
                        }
                    }
                }
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
                .padding(16.dp)
        ) {
            // Section 0 — Status and time
            AnimatedVisibility(
                visible = sectionVisible[0].value,
                enter = fadeIn(SwooshMotion.quick()) + scaleIn(initialScale = 0.8f, animationSpec = SwooshMotion.bouncy())
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    StatusBadge(post)
                    Text(
                        text = formatRelativeTime(post.publishedAt ?: post.createdAt),
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

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

            // Section 1 — Full text content
            AnimatedVisibility(
                visible = sectionVisible[1].value,
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Text(
                    text = post.textContent,
                    style = MaterialTheme.typography.bodyLarge
                )
            }

            // Section 2 — Tags
            AnimatedVisibility(
                visible = sectionVisible[2].value && post.tags.isNotEmpty(),
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(12.dp))
                    FlowRow(
                        horizontalArrangement = Arrangement.spacedBy(6.dp),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        post.tags.forEach { tag ->
                            SuggestionChip(
                                onClick = {},
                                label = {
                                    Text("#$tag", style = MaterialTheme.typography.labelMedium)
                                },
                                colors = SuggestionChipDefaults.suggestionChipColors(
                                    containerColor = MaterialTheme.colorScheme.secondaryContainer,
                                    labelColor = MaterialTheme.colorScheme.onSecondaryContainer
                                ),
                                border = null
                            )
                        }
                    }
                }
            }

            // Section 3 — Image gallery
            AnimatedVisibility(
                visible = sectionVisible[3].value && allImages.isNotEmpty(),
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))
                    DetailImageGallery(
                        images = allImages,
                        onImageClick = { index ->
                            galleryStartIndex = index
                            showGallery = true
                        }
                    )
                    // Alt text display
                    if (!post.imageAlt.isNullOrBlank()) {
                        Spacer(modifier = Modifier.height(6.dp))
                        Text(
                            text = "Alt: ${post.imageAlt}",
                            style = MaterialTheme.typography.bodySmall.copy(
                                fontStyle = FontStyle.Italic
                            ),
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            // Section 4 — Video player
            AnimatedVisibility(
                visible = sectionVisible[4].value && post.videoUrl != null,
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))
                    VideoPlayer(url = post.videoUrl!!, compact = false)
                }
            }

            // Section 5 — Audio player
            AnimatedVisibility(
                visible = sectionVisible[5].value && post.audioUrl != null,
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))
                    AudioPlayer(url = post.audioUrl!!)
                }
            }

            // Section 6 — Link preview
            AnimatedVisibility(
                visible = sectionVisible[6].value && post.linkUrl != null,
                enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(16.dp))
                    OutlinedCard(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(12.dp)) {
                            if (post.linkImageUrl != null) {
                                AsyncImage(
                                    model = post.linkImageUrl,
                                    contentDescription = null,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(160.dp)
                                        .clip(MaterialTheme.shapes.small),
                                    contentScale = ContentScale.Crop
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                            }
                            if (post.linkTitle != null) {
                                Text(
                                    text = post.linkTitle,
                                    style = MaterialTheme.typography.titleMedium
                                )
                            }
                            if (post.linkDescription != null) {
                                Spacer(modifier = Modifier.height(4.dp))
                                Text(
                                    text = post.linkDescription,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            Spacer(modifier = Modifier.height(4.dp))
                            if (post.linkUrl != null) {
                                Text(
                                    text = post.linkUrl,
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }
                }
            }

            // File attachment
            if (post.fileUrl != null) {
                AnimatedVisibility(
                    visible = sectionVisible[6].value,
                    enter = fadeIn(SwooshMotion.quick()) + slideInVertically(initialOffsetY = { 20 }, animationSpec = SwooshMotion.gentle())
                ) {
                    Column {
                        Spacer(modifier = Modifier.height(16.dp))
                        FileAttachmentCard(
                            fileUrl = post.fileUrl,
                            fileName = post.fileName ?: "File"
                        )
                    }
                }
            }

            // Section 7 — PostStatsSection
            AnimatedVisibility(
                visible = sectionVisible[7].value,
                enter = slideInVertically(initialOffsetY = { it / 4 }, animationSpec = SwooshMotion.gentle()) + fadeIn(SwooshMotion.quick())
            ) {
                Column {
                    Spacer(modifier = Modifier.height(24.dp))
                    PostStatsSection(post)
                }
            }

            // Email-only info card
            if (post.status == "sent" || post.emailOnly) {
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Email,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onErrorContainer,
                            modifier = Modifier.size(24.dp)
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text(
                                text = "\u2709 SENT VIA EMAIL ONLY",
                                style = MaterialTheme.typography.labelLarge,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "This post is not visible on your blog.",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.8f)
                            )
                        }
                    }
                }
            }
        }
    }

    // D3: Animated delete dialog
    if (showDeleteDialog) {
        ConfirmationDialog(
            title = "Delete Post",
            message = "Are you sure you want to delete this post? This action cannot be undone.",
            confirmLabel = "Delete",
            onConfirm = {
                showDeleteDialog = false
                onDelete(post)
            },
            onDismiss = { showDeleteDialog = false }
        )
    }

    // Full-screen gallery
    if (showGallery && allImages.isNotEmpty()) {
        FullScreenGallery(
            images = allImages,
            startIndex = galleryStartIndex,
            onDismiss = { showGallery = false }
        )
    }
}

/**
 * Scrollable image gallery for the detail screen.
 * Shows all images in a column with tap-to-zoom.
 */
@Composable
fun DetailImageGallery(
    images: List<String>,
    onImageClick: (Int) -> Unit
) {
    Column(
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        images.forEachIndexed { index, imageUrl ->
            AsyncImage(
                model = imageUrl,
                contentDescription = "Image ${index + 1} of ${images.size}",
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(MaterialTheme.shapes.medium)
                    .clickable { onImageClick(index) },
                contentScale = ContentScale.FillWidth
            )
        }
    }
}

@Composable
private fun PostStatsSection(post: FeedPost) {
    val stats = remember(post.textContent, post.imageUrl, post.linkUrl) {
        PostStats.fromFeedPost(post)
    }
    var expanded by remember { mutableStateOf(false) }

    OutlinedCard(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // Header row - always visible, clickable to expand
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Post Statistics",
                    style = MaterialTheme.typography.titleSmall
                )
                IconButton(
                    onClick = { expanded = !expanded },
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                        contentDescription = if (expanded) "Collapse" else "Expand",
                        modifier = Modifier.size(20.dp)
                    )
                }
            }

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

            // Quick stats row - always visible
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                StatItem(
                    icon = Icons.Default.TextFields,
                    value = "${stats.wordCount}",
                    label = "Words"
                )
                StatItem(
                    icon = Icons.AutoMirrored.Filled.Article,
                    value = "${stats.charCount}",
                    label = "Chars"
                )
                StatItem(
                    icon = Icons.Default.AccessTime,
                    value = PostStats.formatReadingTime(stats.readingTimeMinutes).ifEmpty { "< 1 min" },
                    label = "Read"
                )
            }

            // Expandable details
            AnimatedVisibility(
                visible = expanded,
                enter = expandVertically(),
                exit = shrinkVertically()
            ) {
                Column(modifier = Modifier.padding(top = 12.dp)) {
                    HorizontalDivider()
                    Spacer(modifier = Modifier.height(12.dp))

                    MetadataRow("Status", post.status.replaceFirstChar { it.uppercase() })
                    if (post.createdAt != null) {
                        MetadataRow("Created", post.createdAt)
                    }
                    if (post.updatedAt != null) {
                        MetadataRow("Updated", post.updatedAt)
                    }
                    if (post.publishedAt != null) {
                        MetadataRow("Published", post.publishedAt)
                    }
                    if (post.featured) {
                        MetadataRow("Featured", "Pinned")
                    }
                    val allImages = if (post.imageUrls.isNotEmpty()) post.imageUrls
                        else if (post.imageUrl != null) listOf(post.imageUrl)
                        else emptyList()
                    if (allImages.isNotEmpty()) {
                        MetadataRow("Images", "${allImages.size}")
                    }

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

                    // Content indicators
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        if (stats.hasImage) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Icon(
                                    Icons.Default.Image,
                                    contentDescription = null,
                                    modifier = Modifier.size(14.dp),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    "Image",
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                        if (stats.hasLink) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Icon(
                                    Icons.Default.Link,
                                    contentDescription = null,
                                    modifier = Modifier.size(14.dp),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    "Link",
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun StatItem(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    value: String,
    label: String
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(18.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = value,
            style = MaterialTheme.typography.titleSmall
        )
        Text(
            text = label,
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun MetadataRow(label: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodyMedium
        )
    }
}
