package com.swoosh.microblog.ui.stats

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Article
import androidx.compose.material.icons.filled.*
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.swoosh.microblog.data.model.GhostTagFull
import com.swoosh.microblog.ui.tags.parseHexColor

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StatsScreen(
    viewModel: StatsViewModel = viewModel(),
    onNavigateToMembers: (() -> Unit)? = null
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()

    // Animated counters -- numbers count up from 0 when data loads
    val animatedTotal by animateIntAsState(
        targetValue = state.stats.totalPosts,
        animationSpec = tween(400),
        label = "totalPosts"
    )
    val animatedPublished by animateIntAsState(
        targetValue = state.stats.publishedCount,
        animationSpec = tween(400),
        label = "published"
    )
    val animatedDrafts by animateIntAsState(
        targetValue = state.stats.draftCount,
        animationSpec = tween(400),
        label = "drafts"
    )
    val animatedScheduled by animateIntAsState(
        targetValue = state.stats.scheduledCount,
        animationSpec = tween(400),
        label = "scheduled"
    )

    // Member stat animations
    val memberStats = state.memberStats
    val animatedMembersTotal by animateIntAsState(
        targetValue = memberStats?.total ?: 0,
        animationSpec = tween(400),
        label = "membersTotal"
    )
    val animatedMembersNew by animateIntAsState(
        targetValue = memberStats?.newThisWeek ?: 0,
        animationSpec = tween(400),
        label = "membersNew"
    )
    val animatedMembersFree by animateIntAsState(
        targetValue = memberStats?.free ?: 0,
        animationSpec = tween(400),
        label = "membersFree"
    )
    val animatedMembersPaid by animateIntAsState(
        targetValue = memberStats?.paid ?: 0,
        animationSpec = tween(400),
        label = "membersPaid"
    )
    val animatedMembersMrr by animateIntAsState(
        targetValue = memberStats?.mrr ?: 0,
        animationSpec = tween(400),
        label = "membersMrr"
    )
    val animatedOpenRate by animateFloatAsState(
        targetValue = memberStats?.avgOpenRate?.toFloat() ?: 0f,
        animationSpec = tween(400),
        label = "openRate"
    )

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Statistics") },
                actions = {
                    IconButton(onClick = { viewModel.loadStats() }) {
                        Icon(Icons.Default.Refresh, contentDescription = "Refresh")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Post counts section
            Text(
                "Posts Overview",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold
            )

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                StatsCard(
                    modifier = Modifier.weight(1f),
                    value = "$animatedTotal",
                    label = "Total Posts",
                    icon = Icons.AutoMirrored.Filled.Article
                )
                StatsCard(
                    modifier = Modifier.weight(1f),
                    value = "$animatedPublished",
                    label = "Published",
                    icon = Icons.Default.Create
                )
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                StatsCard(
                    modifier = Modifier.weight(1f),
                    value = "$animatedDrafts",
                    label = "Drafts",
                    icon = Icons.Default.TextFields
                )
                StatsCard(
                    modifier = Modifier.weight(1f),
                    value = "$animatedScheduled",
                    label = "Scheduled",
                    icon = Icons.Default.Schedule
                )
            }

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

            // Tags section
            if (state.tagStats.isNotEmpty()) {
                Text(
                    "Tags",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold
                )

                OutlinedCard(modifier = Modifier.fillMaxWidth()) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        // Most used tag
                        if (state.mostUsedTag != null) {
                            WritingStatRow(
                                "Most used tag",
                                "#${state.mostUsedTag!!.name} (${state.mostUsedTag!!.count?.posts ?: 0})"
                            )
                            HorizontalDivider()
                        }

                        // Posts without tags
                        WritingStatRow(
                            "Posts without tags",
                            "${state.postsWithoutTags}"
                        )

                        HorizontalDivider()

                        // Total tags
                        WritingStatRow(
                            "Total tags",
                            "${state.tagStats.size}"
                        )

                        // Tag progress bars
                        val maxCount = state.tagStats.maxOfOrNull { it.count?.posts ?: 0 } ?: 1

                        state.tagStats.take(10).forEach { tag ->
                            TagProgressBar(
                                tag = tag,
                                maxCount = maxCount.coerceAtLeast(1)
                            )
                        }
                    }
                }

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

            // Writing stats section
            Text(
                "Writing Stats",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold
            )

            OutlinedCard(modifier = Modifier.fillMaxWidth()) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    WritingStatRow("Total words written", "${state.stats.totalWords}")
                    HorizontalDivider()
                    WritingStatRow("Total characters", "${state.stats.totalCharacters}")
                    HorizontalDivider()
                    WritingStatRow("Average post length", "${state.stats.averageWordCount} words")
                    HorizontalDivider()
                    WritingStatRow("Average characters", "${state.stats.averageCharCount} chars")
                    HorizontalDivider()
                    WritingStatRow("Longest post", "${state.stats.longestPostWords} words")
                    HorizontalDivider()
                    WritingStatRow("Shortest post", "${state.stats.shortestPostWords} words")
                }
            }

            // Members section
            if (memberStats != null) {
                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    "Members",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold
                )

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = "$animatedMembersTotal",
                        label = "Total",
                        icon = Icons.Default.People
                    )
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = "+$animatedMembersNew",
                        label = "New this week",
                        icon = Icons.Default.PersonAdd
                    )
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = "${String.format("%.1f", animatedOpenRate)}%",
                        label = "Open rate",
                        icon = Icons.Default.MailOutline
                    )
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = "$animatedMembersFree",
                        label = "Free",
                        icon = Icons.Default.Person
                    )
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = "$animatedMembersPaid",
                        label = "Paid",
                        icon = Icons.Default.Diamond
                    )
                    MemberStatsCard(
                        modifier = Modifier.weight(1f),
                        value = formatMrr(animatedMembersMrr),
                        label = "MRR",
                        icon = Icons.Default.AttachMoney
                    )
                }

                if (onNavigateToMembers != null) {
                    TextButton(
                        onClick = onNavigateToMembers,
                        modifier = Modifier.align(Alignment.End)
                    ) {
                        Text("See all members")
                        Spacer(modifier = Modifier.width(4.dp))
                        Icon(
                            Icons.Default.ChevronRight,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                }
            }

            if (state.error != null) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Note: Remote post data may be incomplete. ${state.error}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

private fun formatMrr(cents: Int): String {
    val dollars = cents / 100.0
    return if (dollars >= 1000) {
        String.format("$%.1fk", dollars / 1000)
    } else {
        String.format("$%.0f", dollars)
    }
}

@Composable
private fun TagProgressBar(
    tag: GhostTagFull,
    maxCount: Int
) {
    val postCount = tag.count?.posts ?: 0
    val progress = postCount.toFloat() / maxCount.toFloat()
    val animatedProgress by animateFloatAsState(
        targetValue = progress,
        animationSpec = tween(600),
        label = "tagProgress_${tag.name}"
    )

    val barColor = tag.accent_color?.let { parseHexColor(it) }
        ?: MaterialTheme.colorScheme.primary

    Column(modifier = Modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.weight(1f)
            ) {
                Box(
                    modifier = Modifier
                        .size(8.dp)
                        .clip(CircleShape)
                        .background(barColor)
                )
                Text(
                    text = tag.name,
                    style = MaterialTheme.typography.bodySmall,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            Text(
                text = "$postCount",
                style = MaterialTheme.typography.labelMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

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

        LinearProgressIndicator(
            progress = { animatedProgress },
            modifier = Modifier
                .fillMaxWidth()
                .height(6.dp)
                .clip(RoundedCornerShape(3.dp)),
            color = barColor,
            trackColor = MaterialTheme.colorScheme.surfaceVariant
        )
    }
}

@Composable
private fun StatsCard(
    modifier: Modifier = Modifier,
    value: String,
    label: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    OutlinedCard(modifier = modifier) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = value,
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface
            )
            Text(
                text = label,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun MemberStatsCard(
    modifier: Modifier = Modifier,
    value: String,
    label: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    ElevatedCard(modifier = modifier) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(20.dp)
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = value,
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface
            )
            Text(
                text = label,
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun WritingStatRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Text(
            text = value,
            style = MaterialTheme.typography.titleSmall,
            fontWeight = FontWeight.Medium
        )
    }
}
