package com.omixlab.lckcontrol.ui.plans

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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.omixlab.lckcontrol.shared.StreamDestination
import com.omixlab.lckcontrol.streaming.StreamingState
import com.omixlab.lckcontrol.ui.components.GameInfoRow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlanDetailScreen(
    planId: String,
    onBack: () -> Unit,
    onNavigateToEditPlan: (String) -> Unit = {},
    viewModel: PlanDetailViewModel = hiltViewModel(),
) {
    val plan by viewModel.plan.collectAsStateWithLifecycle()
    val isLoading by viewModel.isLoading.collectAsStateWithLifecycle()
    val error by viewModel.error.collectAsStateWithLifecycle()
    val streamingState by viewModel.streamingState.collectAsStateWithLifecycle()
    val streamingStats by viewModel.streamingStats.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(error) {
        error?.let {
            snackbarHostState.showSnackbar(it)
            viewModel.clearError()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(plan?.name ?: "Plan Detail") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    if (plan?.status == "DRAFT") {
                        IconButton(onClick = { onNavigateToEditPlan(planId) }) {
                            Icon(Icons.Default.Edit, contentDescription = "Edit")
                        }
                    }
                    if (plan?.status != "LIVE") {
                        IconButton(onClick = { viewModel.deletePlan(onBack) }) {
                            Icon(Icons.Default.Delete, contentDescription = "Delete")
                        }
                    }
                },
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
    ) { padding ->
        val currentPlan = plan
        if (currentPlan == null) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
            ) {
                CircularProgressIndicator()
            }
            return@Scaffold
        }

        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(horizontal = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            item {
                Spacer(Modifier.height(8.dp))

                // Status
                ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text("Status", style = MaterialTheme.typography.labelMedium)
                        Spacer(Modifier.height(4.dp))
                        Text(
                            currentPlan.status,
                            style = MaterialTheme.typography.headlineSmall,
                            color = when (currentPlan.status) {
                                "LIVE" -> MaterialTheme.colorScheme.error
                                "READY" -> MaterialTheme.colorScheme.primary
                                else -> MaterialTheme.colorScheme.onSurface
                            },
                        )
                    }
                }
            }

            // Execution mode
            item {
                ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text("Execution Mode", style = MaterialTheme.typography.labelMedium)
                        Spacer(Modifier.height(4.dp))
                        Text(
                            when (currentPlan.executionMode) {
                                "APP_STREAMING" -> "App Streaming"
                                else -> "In-Game"
                            },
                            style = MaterialTheme.typography.bodyMedium,
                        )
                    }
                }
            }

            // Game
            if (currentPlan.gameId.isNotBlank()) {
                item {
                    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(16.dp)) {
                            Text("Game", style = MaterialTheme.typography.labelMedium)
                            Spacer(Modifier.height(4.dp))
                            GameInfoRow(
                                packageName = currentPlan.gameId,
                                gameInfoProvider = viewModel.gameInfoProvider,
                                showPackageName = true,
                            )
                        }
                    }
                }
            }


            // Action buttons
            item {
                when (currentPlan.status) {
                    "DRAFT" -> {
                        Button(
                            onClick = viewModel::preparePlan,
                            modifier = Modifier.fillMaxWidth(),
                            enabled = !isLoading,
                        ) {
                            if (isLoading) CircularProgressIndicator()
                            else Text("Prepare Stream")
                        }
                    }
                    "READY" -> {
                        Button(
                            onClick = viewModel::startPlan,
                            modifier = Modifier.fillMaxWidth(),
                            enabled = !isLoading,
                        ) {
                            Text("Go Live")
                        }
                    }
                    "LIVE" -> {
                        OutlinedButton(
                            onClick = viewModel::endPlan,
                            modifier = Modifier.fillMaxWidth(),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = MaterialTheme.colorScheme.error,
                            ),
                            enabled = !isLoading,
                        ) {
                            Text("End Stream")
                        }
                    }
                }
            }

            // Stream preview + stats (when LIVE + APP_STREAMING)
            if (currentPlan.status == "LIVE" &&
                currentPlan.executionMode == "APP_STREAMING" &&
                streamingState == StreamingState.LIVE
            ) {
                item {
                    Text("Stream Preview", style = MaterialTheme.typography.titleMedium)
                    Spacer(Modifier.height(8.dp))
                    StreamPreviewSurface(streamingManager = viewModel.streamingManager)
                }
                item {
                    StreamingStatsCard(stats = streamingStats)
                }
            }

            // Destinations
            item {
                Spacer(Modifier.height(8.dp))
                Text("Destinations", style = MaterialTheme.typography.titleMedium)
            }

            items(currentPlan.destinations) { dest ->
                DestinationDetailCard(dest)
            }

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

@Composable
private fun DestinationDetailCard(destination: StreamDestination) {
    val clipboardManager = LocalClipboardManager.current

    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(4.dp),
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(destination.service, style = MaterialTheme.typography.titleSmall)
                Text(
                    destination.status,
                    style = MaterialTheme.typography.labelSmall,
                    color = if (destination.status == "READY") MaterialTheme.colorScheme.primary
                    else MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }

            Text(destination.title, style = MaterialTheme.typography.bodyMedium)

            if (destination.rtmpUrl.isNotBlank()) {
                Spacer(Modifier.height(4.dp))
                Text("RTMP URL", style = MaterialTheme.typography.labelSmall)
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        destination.rtmpUrl,
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.weight(1f),
                    )
                    IconButton(onClick = {
                        clipboardManager.setText(AnnotatedString(destination.rtmpUrl))
                    }) {
                        Icon(Icons.Default.ContentCopy, contentDescription = "Copy", modifier = Modifier.padding(4.dp))
                    }
                }
            }

            if (destination.streamKey.isNotBlank()) {
                Text("Stream Key", style = MaterialTheme.typography.labelSmall)
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        destination.streamKey.take(8) + "...",
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.weight(1f),
                    )
                    IconButton(onClick = {
                        clipboardManager.setText(AnnotatedString(destination.streamKey))
                    }) {
                        Icon(Icons.Default.ContentCopy, contentDescription = "Copy", modifier = Modifier.padding(4.dp))
                    }
                }
            }
        }
    }
}
