package com.omixlab.lckcontrol.ui.dashboard

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.automirrored.filled.Chat
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.ClearAll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.omixlab.lckcontrol.shared.StreamPlan
import com.omixlab.lckcontrol.streaming.StreamingState
import com.omixlab.lckcontrol.ui.components.GameInfoRow
import com.omixlab.lckcontrol.ui.plans.StreamPreviewSurface
import com.omixlab.lckcontrol.ui.plans.StreamingStatsCard
import com.omixlab.lckcontrol.util.GameInfoProvider

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DashboardScreen(
    onNavigateToCreatePlan: () -> Unit,
    onNavigateToPlan: (String) -> Unit,
    onNavigateToChat: (planId: String, service: String, destinationId: String) -> Unit = { _, _, _ -> },
    viewModel: DashboardViewModel = hiltViewModel(),
) {
    val plans by viewModel.plans.collectAsStateWithLifecycle()
    val backendHealthy by viewModel.backendHealthy.collectAsStateWithLifecycle()
    val backendVersion by viewModel.backendVersion.collectAsStateWithLifecycle()
    val defaultExecutionMode by viewModel.defaultExecutionMode.collectAsStateWithLifecycle()
    val streamingState by viewModel.streamingState.collectAsStateWithLifecycle()
    val streamingStats by viewModel.streamingStats.collectAsStateWithLifecycle()
    val unreadCounts by viewModel.unreadCounts.collectAsStateWithLifecycle()

    Scaffold(
        topBar = {
            TopAppBar(title = { Text("LCK Control") })
        },
        floatingActionButton = {
            FloatingActionButton(onClick = onNavigateToCreatePlan) {
                Icon(Icons.Default.Add, contentDescription = "Create Plan")
            }
        },
    ) { padding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(horizontal = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            item {
                Spacer(Modifier.height(8.dp))
                Text("Server Status", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(4.dp))
                ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        val (color, label) = when (backendHealthy) {
                            true -> MaterialTheme.colorScheme.primary to "Connected"
                            false -> MaterialTheme.colorScheme.error to "Unreachable"
                            null -> MaterialTheme.colorScheme.outline to "Checking..."
                        }
                        Icon(
                            Icons.Default.Circle,
                            contentDescription = label,
                            tint = color,
                            modifier = Modifier.size(12.dp),
                        )
                        Spacer(Modifier.width(12.dp))
                        Column {
                            Text("Backend", style = MaterialTheme.typography.titleSmall)
                            Text(label, style = MaterialTheme.typography.bodySmall, color = color)
                            if (backendVersion != null) {
                                Text(
                                    "v$backendVersion",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                )
                            }
                        }
                    }
                }
            }

            // Live preview + streaming stats (only for APP_STREAMING plans with active engine)
            val hasLiveAppStreaming = plans.any {
                it.status == "LIVE" && it.executionMode == "APP_STREAMING"
            }
            if (hasLiveAppStreaming && streamingState == StreamingState.LIVE) {
                item {
                    Spacer(Modifier.height(8.dp))
                    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(16.dp)) {
                            Text("Live Preview", style = MaterialTheme.typography.labelMedium)
                            Spacer(Modifier.height(8.dp))
                            StreamPreviewSurface(
                                streamingManager = viewModel.streamingManagerInstance,
                            )
                        }
                    }
                }
                item {
                    StreamingStatsCard(stats = streamingStats)
                }
            }

            // Live Chat section — only when a LIVE plan has YouTube/Twitch destinations
            val liveChatDestinations = plans.flatMap { plan ->
                if (plan.status == "LIVE") {
                    plan.destinations.filter {
                        it.service == "YOUTUBE" || it.service == "TWITCH"
                    }.map { dest -> Triple(plan.planId, dest.service, dest) }
                } else emptyList()
            }
            if (liveChatDestinations.isNotEmpty()) {
                item {
                    Spacer(Modifier.height(8.dp))
                    Text("Live Chat", style = MaterialTheme.typography.titleMedium)
                    Spacer(Modifier.height(4.dp))
                }
                items(liveChatDestinations, key = { "${it.first}:${it.second}:${it.third.linkedAccountId}" }) { (planId, service, dest) ->
                    val chatKey = "$planId:$service:${dest.linkedAccountId}"
                    val unread = unreadCounts[chatKey] ?: 0
                    ChatServiceCard(
                        service = service,
                        unreadCount = unread,
                        onClick = { onNavigateToChat(planId, service, dest.linkedAccountId) },
                    )
                }
            }

            item {
                Spacer(Modifier.height(8.dp))
                Text("Default Streaming Mode", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(4.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    FilterChip(
                        selected = defaultExecutionMode == "IN_GAME",
                        onClick = { viewModel.setDefaultExecutionMode("IN_GAME") },
                        label = { Text("In-Game") },
                    )
                    FilterChip(
                        selected = defaultExecutionMode == "APP_STREAMING",
                        onClick = { viewModel.setDefaultExecutionMode("APP_STREAMING") },
                        label = { Text("App Streaming") },
                    )
                }
            }

            item {
                Spacer(Modifier.height(8.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text("Stream Plans", style = MaterialTheme.typography.titleMedium)
                    if (plans.any { it.status == "ENDED" }) {
                        IconButton(onClick = viewModel::clearEndedPlans) {
                            Icon(
                                Icons.Default.ClearAll,
                                contentDescription = "Clear ended plans",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                            )
                        }
                    }
                }
            }

            if (plans.isEmpty()) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant,
                        ),
                    ) {
                        Text(
                            "No stream plans yet. Tap + to create one.",
                            modifier = Modifier.padding(16.dp),
                            style = MaterialTheme.typography.bodyMedium,
                        )
                    }
                }
            } else {
                items(plans, key = { it.planId }) { plan ->
                    PlanCard(
                        plan = plan,
                        gameInfoProvider = viewModel.gameInfoProvider,
                        onClick = { onNavigateToPlan(plan.planId) },
                    )
                }
            }

            item { Spacer(Modifier.height(80.dp)) }
        }
    }
}

@Composable
private fun PlanCard(
    plan: StreamPlan,
    gameInfoProvider: GameInfoProvider,
    onClick: () -> Unit,
) {
    ElevatedCard(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text(plan.name, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
                Spacer(Modifier.width(8.dp))
                StatusChip(plan.status)
            }
            Spacer(Modifier.height(4.dp))
            Text(
                "${plan.destinations.size} destination(s)",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            if (plan.gameId.isNotBlank()) {
                Spacer(Modifier.height(8.dp))
                GameInfoRow(
                    packageName = plan.gameId,
                    gameInfoProvider = gameInfoProvider,
                    iconSize = 24.dp,
                )
            }
        }
    }
}

private val YouTubeRed = Color(0xFFFF0000)
private val TwitchPurple = Color(0xFF9146FF)

@Composable
private fun ChatServiceCard(
    service: String,
    unreadCount: Int,
    onClick: () -> Unit,
) {
    val serviceColor = if (service == "YOUTUBE") YouTubeRed else TwitchPurple
    val serviceLabel = if (service == "YOUTUBE") "YouTube Chat" else "Twitch Chat"

    ElevatedCard(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(
                Icons.AutoMirrored.Filled.Chat,
                contentDescription = serviceLabel,
                tint = serviceColor,
                modifier = Modifier.size(24.dp),
            )
            Spacer(Modifier.width(12.dp))
            Text(
                serviceLabel,
                style = MaterialTheme.typography.titleSmall,
                modifier = Modifier.weight(1f),
            )
            if (unreadCount > 0) {
                BadgedBox(badge = {
                    Badge { Text(if (unreadCount > 99) "99+" else unreadCount.toString()) }
                }) {}
            }
        }
    }
}

@Composable
private fun StatusChip(status: String) {
    val color = when (status) {
        "LIVE" -> MaterialTheme.colorScheme.error
        "READY" -> MaterialTheme.colorScheme.primary
        "PREPARING" -> MaterialTheme.colorScheme.tertiary
        "ENDED" -> MaterialTheme.colorScheme.outline
        else -> MaterialTheme.colorScheme.onSurfaceVariant
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        Icon(
            Icons.Default.Circle,
            contentDescription = null,
            tint = color,
            modifier = Modifier.height(8.dp).width(8.dp),
        )
        Spacer(Modifier.width(4.dp))
        Text(status, style = MaterialTheme.typography.labelSmall, color = color)
    }
}
