package com.devlab.app.ui.servers

import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
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.Brush
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.devlab.app.data.model.ServiceInfo
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.devlab.app.ui.components.LoadingIndicator
import com.devlab.app.ui.components.MetricsChart
import com.devlab.app.ui.components.StatCard
import com.devlab.app.ui.theme.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerDetailScreen(
    serverId: Int,
    onBack: () -> Unit,
    viewModel: ServerDetailViewModel = viewModel()
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()

    LaunchedEffect(serverId) {
        viewModel.load(serverId)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(state.server?.name ?: "Server Detail") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = MaterialTheme.colorScheme.onPrimary,
                    navigationIconContentColor = MaterialTheme.colorScheme.onPrimary
                ),
                modifier = Modifier.background(
                    Brush.horizontalGradient(
                        colors = listOf(
                            MaterialTheme.colorScheme.primary,
                            MaterialTheme.colorScheme.primary.copy(alpha = 0.85f)
                        )
                    )
                )
            )
        }
    ) { padding ->
        when {
            state.isLoading -> LoadingIndicator(modifier = Modifier.padding(padding))
            state.error != null -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(padding),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(Icons.Default.ErrorOutline, contentDescription = null, modifier = Modifier.size(48.dp), tint = MaterialTheme.colorScheme.error)
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(text = state.error ?: "", color = MaterialTheme.colorScheme.error)
                        Spacer(modifier = Modifier.height(16.dp))
                        OutlinedButton(onClick = { viewModel.load(serverId) }) { Text("Retry") }
                    }
                }
            }
            else -> {
                Column(modifier = Modifier.fillMaxSize().padding(padding)) {
                    ScrollableTabRow(
                        selectedTabIndex = state.selectedTab,
                        containerColor = MaterialTheme.colorScheme.surface,
                        contentColor = MaterialTheme.colorScheme.primary,
                        divider = {},
                        edgePadding = 8.dp
                    ) {
                        Tab(
                            selected = state.selectedTab == 0,
                            onClick = { viewModel.selectTab(0) },
                            icon = { Icon(Icons.Default.Info, contentDescription = null, modifier = Modifier.size(18.dp)) },
                            text = { Text("Info") }
                        )
                        Tab(
                            selected = state.selectedTab == 1,
                            onClick = { viewModel.selectTab(1) },
                            icon = { Icon(Icons.Default.StackedLineChart, contentDescription = null, modifier = Modifier.size(18.dp)) },
                            text = { Text("Metrics") }
                        )
                        Tab(
                            selected = state.selectedTab == 2,
                            onClick = { viewModel.selectTab(2) },
                            icon = { Icon(Icons.Default.Terminal, contentDescription = null, modifier = Modifier.size(18.dp)) },
                            text = { Text("Console") }
                        )
                        Tab(
                            selected = state.selectedTab == 3,
                            onClick = { viewModel.selectTab(3) },
                            icon = { Icon(Icons.Default.MiscellaneousServices, contentDescription = null, modifier = Modifier.size(18.dp)) },
                            text = { Text("Services") }
                        )
                        Tab(
                            selected = state.selectedTab == 4,
                            onClick = { viewModel.selectTab(4) },
                            icon = { Icon(Icons.Default.Bolt, contentDescription = null, modifier = Modifier.size(18.dp)) },
                            text = { Text("Actions") }
                        )
                    }

                    when (state.selectedTab) {
                        0 -> InfoTab(state)
                        1 -> MetricsTab(state)
                        2 -> ConsoleTab(state, viewModel)
                        3 -> ServicesTab(state, viewModel)
                        4 -> ActionsTab(state, viewModel)
                    }
                }
            }
        }
    }
}

@Composable
private fun InfoTab(state: ServerDetailUiState) {
    val server = state.server ?: return
    val metrics = state.metrics

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        val statusColor = when (server.status) {
            "online" -> Green500
            "offline" -> Red500
            "disabled" -> Grey500
            else -> Orange500
        }

        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(imageVector = Icons.Default.Dns, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = server.name, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold)
                }
                Spacer(modifier = Modifier.height(8.dp))
                Surface(color = statusColor.copy(alpha = 0.15f), shape = RoundedCornerShape(8.dp)) {
                    Row(modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
                        Box(modifier = Modifier.size(8.dp).clip(RoundedCornerShape(4.dp)).background(statusColor))
                        Spacer(modifier = Modifier.width(6.dp))
                        Text(text = server.status.replaceFirstChar { it.uppercase() }, color = statusColor, style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Medium)
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
                InfoRow("IP Address", server.ip_address)
                InfoRow("SSH Port", server.ssh_port.toString())
                if (server.group_name != null) InfoRow("Group", server.group_name)
                if (server.description != null) InfoRow("Description", server.description)
                if (server.created_by_name != null) InfoRow("Created By", server.created_by_name)
            }
        }

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

        if (metrics != null) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(imageVector = Icons.Default.Memory, contentDescription = null, tint = Orange500)
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(text = "Current Metrics", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                    }
                    Spacer(modifier = Modifier.height(12.dp))
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                        StatCard("CPU", "${metrics.cpu_usage?.toInt() ?: 0}%", Orange500, icon = Icons.Default.Memory, modifier = Modifier.weight(1f))
                        StatCard("RAM", "${metrics.ram_usage?.toInt() ?: 0}%", Blue700, icon = Icons.Default.Storage, modifier = Modifier.weight(1f))
                        StatCard("Disk", "${metrics.disk_usage?.toInt() ?: 0}%", Green500, icon = Icons.Default.SdStorage, modifier = Modifier.weight(1f))
                    }
                    if (metrics.uptime != null) {
                        Spacer(modifier = Modifier.height(12.dp))
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(Icons.Default.Schedule, contentDescription = null, tint = Grey500, modifier = Modifier.size(16.dp))
                            Spacer(modifier = Modifier.width(6.dp))
                            Text("Uptime: ${metrics.uptime}", style = MaterialTheme.typography.bodySmall, color = Grey700)
                        }
                    }
                    if (metrics.load_average != null) {
                        Spacer(modifier = Modifier.height(4.dp))
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(Icons.Default.TrendingUp, contentDescription = null, tint = Grey500, modifier = Modifier.size(16.dp))
                            Spacer(modifier = Modifier.width(6.dp))
                            Text("Load: ${metrics.load_average}", style = MaterialTheme.typography.bodySmall, color = Grey700)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun InfoRow(label: String, value: String) {
    Row(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween) {
        Text(text = label, style = MaterialTheme.typography.bodyMedium, color = Grey700, modifier = Modifier.weight(0.4f))
        Text(text = value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium, modifier = Modifier.weight(0.6f))
    }
    HorizontalDivider(color = Grey100, thickness = 0.5.dp)
}

@Composable
private fun MetricsTab(state: ServerDetailUiState) {
    if (state.metricsHistory.isEmpty()) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
        return
    }

    Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(imageVector = Icons.Default.StackedLineChart, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = "Last 24 Hours", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                }
                Spacer(modifier = Modifier.height(16.dp))
                MetricsChart(points = state.metricsHistory.takeLast(24), modifier = Modifier.fillMaxWidth())
            }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "Recent Values", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
        Spacer(modifier = Modifier.height(8.dp))

        state.metricsHistory.takeLast(12).reversed().forEach { point ->
            Card(
                modifier = Modifier.fillMaxWidth().padding(vertical = 3.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
            ) {
                Row(modifier = Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
                    Text(text = point.recorded_at?.substringAfterLast(" ")?.substringBeforeLast(":") ?: "", style = MaterialTheme.typography.labelSmall, color = Grey500, modifier = Modifier.weight(0.25f))
                    Text(text = "${point.cpu_usage?.toInt() ?: 0}%", fontWeight = FontWeight.SemiBold, color = Orange500, modifier = Modifier.weight(0.25f))
                    Text(text = "${point.ram_usage?.toInt() ?: 0}%", fontWeight = FontWeight.SemiBold, color = Blue700, modifier = Modifier.weight(0.25f))
                    Text(text = "${point.disk_usage?.toInt() ?: 0}%", fontWeight = FontWeight.SemiBold, color = Green500, modifier = Modifier.weight(0.25f))
                }
            }
        }
    }
}

@Composable
private fun ConsoleTab(state: ServerDetailUiState, viewModel: ServerDetailViewModel) {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(imageVector = Icons.Default.Terminal, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = "Execute Command", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
        }
        Spacer(modifier = Modifier.height(12.dp))
        OutlinedTextField(
            value = state.commandText, onValueChange = viewModel::updateCommand,
            modifier = Modifier.fillMaxWidth(),
            placeholder = { Text("e.g. uptime, df -h, free -m") },
            singleLine = true, enabled = !state.isExecuting,
            leadingIcon = { Icon(Icons.Default.Terminal, contentDescription = null) }
        )
        Spacer(modifier = Modifier.height(8.dp))
        Button(onClick = { viewModel.executeCommand() }, modifier = Modifier.fillMaxWidth(), enabled = state.commandText.isNotBlank() && !state.isExecuting) {
            if (state.isExecuting) {
                CircularProgressIndicator(modifier = Modifier.size(20.dp), color = MaterialTheme.colorScheme.onPrimary, strokeWidth = 2.dp)
            } else {
                Icon(Icons.Default.PlayArrow, contentDescription = null, modifier = Modifier.size(20.dp))
                Spacer(modifier = Modifier.width(6.dp))
                Text("Execute")
            }
        }
        if (state.commandOutput != null) {
            Spacer(modifier = Modifier.height(16.dp))
            Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = Grey900)) {
                Column(modifier = Modifier.padding(12.dp)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(Icons.Default.CheckCircle, contentDescription = null, tint = Green500, modifier = Modifier.size(16.dp))
                        Spacer(modifier = Modifier.width(6.dp))
                        Text("Output", color = Green500, style = MaterialTheme.typography.labelSmall)
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(text = state.commandOutput ?: "", color = Green500, style = MaterialTheme.typography.bodyMedium, fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace)
                }
            }
        }
        if (state.commandError != null) {
            Spacer(modifier = Modifier.height(16.dp))
            Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
                Column(modifier = Modifier.padding(12.dp)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(Icons.Default.Error, contentDescription = null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(16.dp))
                        Spacer(modifier = Modifier.width(6.dp))
                        Text("Error", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.labelSmall)
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(text = state.commandError ?: "", color = MaterialTheme.colorScheme.onErrorContainer, style = MaterialTheme.typography.bodyMedium, fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace)
                }
            }
        }
    }
}

@Composable
private fun ServicesTab(state: ServerDetailUiState, viewModel: ServerDetailViewModel) {
    var showServiceDialog by remember { mutableStateOf(false) }
    var selectedService by remember { mutableStateOf<ServiceInfo?>(null) }
    var serviceQuery by remember { mutableStateOf("") }

    val filtered = remember(state.services, serviceQuery) {
        if (serviceQuery.isBlank()) state.services
        else state.services.filter {
            it.name.contains(serviceQuery, ignoreCase = true) ||
            it.description.contains(serviceQuery, ignoreCase = true)
        }
    }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(imageVector = Icons.Default.MiscellaneousServices, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = "Services", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            Spacer(modifier = Modifier.weight(1f))
            TextButton(onClick = { viewModel.loadServices() }) {
                Icon(Icons.Default.Refresh, contentDescription = null, modifier = Modifier.size(18.dp))
                Spacer(modifier = Modifier.width(4.dp))
                Text("Refresh")
            }
        }
        Spacer(modifier = Modifier.height(8.dp))

        OutlinedTextField(
            value = serviceQuery,
            onValueChange = { serviceQuery = it },
            modifier = Modifier.fillMaxWidth(),
            placeholder = { Text("Search services...") },
            leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
            singleLine = true
        )
        Spacer(modifier = Modifier.height(8.dp))

        if (state.serviceActionRunning != null) {
            LinearProgressIndicator(
                modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
                color = MaterialTheme.colorScheme.primary
            )
        }

        if (state.serviceActionResult != null) {
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = if (state.serviceActionResult?.contains("ed.") == true) Green500.copy(alpha = 0.1f) else MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Row(modifier = Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        Icons.Default.Info, contentDescription = null,
                        tint = if (state.serviceActionResult?.contains("ed.") == true) Green500 else MaterialTheme.colorScheme.error,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = state.serviceActionResult ?: "", style = MaterialTheme.typography.bodySmall)
                }
            }
            Spacer(modifier = Modifier.height(8.dp))
        }

        when {
            state.isLoadingServices -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            }
            state.servicesError != null -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(text = state.servicesError ?: "", color = MaterialTheme.colorScheme.error)
                        Spacer(modifier = Modifier.height(12.dp))
                        OutlinedButton(onClick = { viewModel.loadServices() }) { Text("Retry") }
                    }
                }
            }
            filtered.isEmpty() -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Text(if (serviceQuery.isNotBlank()) "No services match your search" else "No services found", color = Grey500)
                }
            }
            else -> {
                Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
                    filtered.forEach { service ->
                        val isActive = service.status == "active"
                        val isRunning = state.serviceActionRunning == "${service.name}:start" ||
                                state.serviceActionRunning == "${service.name}:stop" ||
                                state.serviceActionRunning == "${service.name}:restart" ||
                                state.serviceActionRunning == "${service.name}:reload"

                        Card(
                            onClick = { selectedService = service; showServiceDialog = true },
                            modifier = Modifier.fillMaxWidth().padding(vertical = 3.dp),
                            enabled = !isRunning,
                            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                            elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                        ) {
                            Row(
                                modifier = Modifier.fillMaxWidth().padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Box(
                                    modifier = Modifier
                                        .size(8.dp)
                                        .clip(RoundedCornerShape(4.dp))
                                        .background(if (isActive) Green500 else Grey500)
                                )
                                Spacer(modifier = Modifier.width(10.dp))
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(text = service.name, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
                                    if (service.description.isNotBlank()) {
                                        Text(text = service.description, style = MaterialTheme.typography.labelSmall, color = Grey500)
                                    }
                                }
                                if (isRunning) {
                                    CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
                                } else {
                                    Text(
                                        text = if (isActive) "Active" else service.status,
                                        color = if (isActive) Green500 else Grey500,
                                        style = MaterialTheme.typography.labelSmall,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (showServiceDialog && selectedService != null) {
        val service = selectedService!!
        val isActive = service.status == "active"

        AlertDialog(
            onDismissRequest = { showServiceDialog = false },
            title = {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        Icons.Default.MiscellaneousServices,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(22.dp)
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(text = service.name, fontWeight = FontWeight.SemiBold)
                }
            },
            text = {
                Column {
                    Surface(
                        color = (if (isActive) Green500 else Grey500).copy(alpha = 0.15f),
                        shape = RoundedCornerShape(8.dp)
                    ) {
                        Row(
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Box(
                                modifier = Modifier
                                    .size(8.dp)
                                    .clip(androidx.compose.foundation.shape.CircleShape)
                                    .background(if (isActive) Green500 else Grey500)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = if (isActive) "Active" else service.status.replaceFirstChar { it.uppercase() },
                                color = if (isActive) Green500 else Grey500,
                                style = MaterialTheme.typography.labelMedium,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }

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

                    Text(
                        text = "Actions",
                        style = MaterialTheme.typography.labelMedium,
                        color = Grey500
                    )
                    Spacer(modifier = Modifier.height(8.dp))

                    if (isActive) {
                        ServiceActionBtn(
                            label = "Restart",
                            icon = Icons.Default.Refresh,
                            color = Orange500,
                            onClick = { viewModel.serviceAction(service.name, "restart"); showServiceDialog = false }
                        )
                        ServiceActionBtn(
                            label = "Stop",
                            icon = Icons.Default.Stop,
                            color = Red500,
                            onClick = { viewModel.serviceAction(service.name, "stop"); showServiceDialog = false }
                        )
                        ServiceActionBtn(
                            label = "Reload",
                            icon = Icons.Default.Autorenew,
                            color = Blue700,
                            onClick = { viewModel.serviceAction(service.name, "reload"); showServiceDialog = false }
                        )
                    } else {
                        ServiceActionBtn(
                            label = "Start",
                            icon = Icons.Default.PlayArrow,
                            color = Green500,
                            onClick = { viewModel.serviceAction(service.name, "start"); showServiceDialog = false }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showServiceDialog = false }) {
                    Text("Cancel")
                }
            },
            containerColor = MaterialTheme.colorScheme.surface,
            shape = RoundedCornerShape(16.dp)
        )
    }
}

@Composable
private fun ServiceActionBtn(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, color: androidx.compose.ui.graphics.Color, onClick: () -> Unit) {
    FilledTonalButton(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth().padding(vertical = 3.dp),
        colors = ButtonDefaults.filledTonalButtonColors(
            containerColor = color.copy(alpha = 0.12f),
            contentColor = color
        )
    ) {
        Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp))
        Spacer(modifier = Modifier.width(8.dp))
        Text(label, fontWeight = FontWeight.SemiBold)
    }
}

@Composable
private fun ActionsTab(state: ServerDetailUiState, viewModel: ServerDetailViewModel) {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(imageVector = Icons.Default.Bolt, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = "Server Actions", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
        }
        Spacer(modifier = Modifier.height(16.dp))

        ActionButton(
            icon = Icons.Default.NetworkCheck,
            label = "Test Connection",
            description = "Check if SSH is reachable",
            isLoading = state.isTestingConnection,
            color = MaterialTheme.colorScheme.primary,
            onClick = { viewModel.testConnection() }
        )

        ActionButton(
            icon = Icons.Default.RestartAlt,
            label = "Reboot Server",
            description = "Restart the server remotely",
            isLoading = state.isActionRunning && state.actionMessage == "Rebooting server...",
            color = Orange500,
            onClick = { viewModel.reboot() }
        )

        ActionButton(
            icon = Icons.Default.PowerSettingsNew,
            label = "Shutdown Server",
            description = "Power off the server remotely",
            isLoading = state.isActionRunning && state.actionMessage == "Shutting down server...",
            color = Red500,
            onClick = { viewModel.shutdown() }
        )

        if (state.actionMessage != null) {
            Spacer(modifier = Modifier.height(16.dp))
            val isSuccess = state.connectionResult == true || (
                state.actionMessage != null &&
                !state.actionMessage!!.contains("failed", ignoreCase = true) &&
                !state.actionMessage!!.contains("error", ignoreCase = true) &&
                state.actionMessage != "Rebooting server..." &&
                state.actionMessage != "Shutting down server..."
            )
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = if (isSuccess) Green500.copy(alpha = 0.1f)
                        else MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Row(modifier = Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        imageVector = if (isSuccess) Icons.Default.CheckCircle else Icons.Default.Error,
                        contentDescription = null,
                        tint = if (isSuccess) Green500 else MaterialTheme.colorScheme.error,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = state.actionMessage ?: "",
                        color = if (isSuccess) Green500 else MaterialTheme.colorScheme.onErrorContainer,
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }
    }
}

@Composable
private fun ActionButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    label: String,
    description: String,
    isLoading: Boolean,
    color: androidx.compose.ui.graphics.Color,
    onClick: () -> Unit
) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
        enabled = !isLoading,
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = color,
                modifier = Modifier.size(28.dp)
            )
            Spacer(modifier = Modifier.width(16.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(text = label, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
                Text(text = description, style = MaterialTheme.typography.bodySmall, color = Grey500)
            }
            if (isLoading) {
                CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
            } else {
                Icon(Icons.Default.KeyboardArrowRight, contentDescription = null, tint = Grey500)
            }
        }
    }
}
