package com.tomhempel.unityudp.ui

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
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.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tomhempel.unityudp.data.ProjectData
import com.tomhempel.unityudp.data.UdpPackageData

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProjectScreen(projectId: String, viewModel: MainViewModel) {
    val projects by viewModel.projects.collectAsState()
    val project = projects.find { it.id == projectId } ?: return
    val isSending by viewModel.isSending.collectAsState()
    val lastSentPackageId by viewModel.lastSentPackageId.collectAsState()
    val sendResult by viewModel.sendResult.collectAsState()

    var showAddPackageDialog by remember { mutableStateOf(false) }
    var editingPackage by remember { mutableStateOf<UdpPackageData?>(null) }
    var deletePackageTarget by remember { mutableStateOf<UdpPackageData?>(null) }
    var showApplyDialog by remember { mutableStateOf<Pair<Int, Boolean>?>(null) }

    // Project settings state — rememberSaveable so rotation doesn't lose unsaved edits.
    // IPs stored as a pipe-separated string to keep rememberSaveable simple.
    var ipInput by rememberSaveable(key = "ipInput_${project.id}") { mutableStateOf("") }
    var portInput by rememberSaveable(key = "port_${project.id}") { mutableStateOf(project.port.toString()) }
    var projectIpsStr by rememberSaveable(key = "ips_${project.id}") {
        mutableStateOf(project.ipAddresses.joinToString("|"))
    }
    var isBroadcast by rememberSaveable(key = "broadcast_${project.id}") { mutableStateOf(project.isBroadcast) }
    var ipError by remember { mutableStateOf<String?>(null) }

    // Derived list view — recomputed whenever the string changes
    val projectIps: List<String> = remember(projectIpsStr) {
        projectIpsStr.split("|").filter { it.isNotEmpty() }
    }
    fun setProjectIps(list: List<String>) { projectIpsStr = list.joinToString("|") }

    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(sendResult) {
        sendResult?.let { result ->
            snackbarHostState.showSnackbar(
                message = result.message,
                duration = SnackbarDuration.Short
            )
            viewModel.clearSendResult()
        }
    }

    BackHandler { viewModel.navigateHome() }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(project.name) },
                navigationIcon = {
                    IconButton(onClick = { viewModel.navigateHome() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                }
            )
        },
        floatingActionButton = {
            ExtendedFloatingActionButton(
                onClick = { showAddPackageDialog = true },
                icon = { Icon(Icons.Default.Add, contentDescription = null) },
                text = { Text("New Package") }
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        LazyVerticalGrid(
            columns = GridCells.Adaptive(minSize = 340.dp),
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .imePadding(),
            contentPadding = PaddingValues(16.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // Settings card - spans full width
            item(span = { GridItemSpan(maxLineSpan) }) {
                ProjectSettingsCard(
                    project = project,
                    ipInput = ipInput,
                    onIpInputChange = { ipInput = it; ipError = null },
                    portInput = portInput,
                    onPortInputChange = { portInput = it },
                    projectIps = projectIps,
                    isBroadcast = isBroadcast,
                    onBroadcastChange = { isBroadcast = it },
                    onAddIp = {
                        val ip = ipInput.trim()
                        when {
                            !isValidIp(ip) -> ipError = "Invalid IP address"
                            projectIps.contains(ip) -> ipError = "IP already added"
                            else -> {
                                setProjectIps(projectIps + ip)
                                ipInput = ""
                            }
                        }
                    },
                    onRemoveIp = { ip ->
                        setProjectIps(projectIps.filter { it != ip })
                    },
                    onApply = {
                        val port = portInput.toIntOrNull()
                        if (port == null || port < 1 || port > 65535) {
                            portInput = project.port.toString()
                        } else {
                            showApplyDialog = Pair(port, true)
                        }
                    },
                    ipError = ipError
                )
            }

            if (project.packages.isEmpty()) {
                item(span = { GridItemSpan(maxLineSpan) }) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            Icon(
                                Icons.Default.Inventory2,
                                contentDescription = null,
                                modifier = Modifier.size(64.dp),
                                tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                            )
                            Spacer(modifier = Modifier.height(16.dp))
                            Text("No packages yet", style = MaterialTheme.typography.titleLarge)
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                "Create your first UDP package",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            } else {
                items(project.packages, key = { it.id }) { pkg ->
                    PackageCard(
                        pkg = pkg,
                        project = project,
                        isSending = isSending,
                        wasSent = lastSentPackageId == pkg.id,
                        onSend = { viewModel.sendPackage(project, pkg) },
                        onEdit = { editingPackage = pkg },
                        onCopy = { viewModel.copyPackage(projectId, pkg) },
                        onDelete = { deletePackageTarget = pkg }
                    )
                }
            }

            item(span = { GridItemSpan(maxLineSpan) }) {
                Spacer(modifier = Modifier.height(72.dp))
            }
        }
    }

    // Apply settings dialog
    showApplyDialog?.let { (port, _) ->
        AlertDialog(
            onDismissRequest = { showApplyDialog = null },
            title = { Text("Apply Settings") },
            text = {
                Text(
                    "Do you want to apply these settings to all packages?\n\n" +
                    "• Yes - All packages will use these settings\n" +
                    "• No - Only project defaults will be updated"
                )
            },
            confirmButton = {
                Button(onClick = {
                    val updatedIps = if (isBroadcast) emptyList() else projectIps.toList()
                    val updatedPackages = project.packages.map { pkg ->
                        pkg.copyWith(ipAddresses = updatedIps, isBroadcast = isBroadcast)
                    }
                    viewModel.updateProject(
                        project.copyWith(
                            ipAddresses = updatedIps,
                            isBroadcast = isBroadcast,
                            port = port,
                            packages = updatedPackages
                        )
                    )
                    showApplyDialog = null
                }) { Text("Yes") }
            },
            dismissButton = {
                TextButton(onClick = {
                    val updatedIps = if (isBroadcast) emptyList() else projectIps.toList()
                    viewModel.updateProject(
                        project.copyWith(
                            ipAddresses = updatedIps,
                            isBroadcast = isBroadcast,
                            port = port
                        )
                    )
                    showApplyDialog = null
                }) { Text("No") }
            }
        )
    }

    if (showAddPackageDialog) {
        PackageDialog(
            pkg = null,
            projectIps = project.ipAddresses,
            onSave = { viewModel.addPackage(projectId, it) },
            onDismiss = { showAddPackageDialog = false }
        )
    }

    editingPackage?.let { pkg ->
        PackageDialog(
            pkg = pkg,
            projectIps = project.ipAddresses,
            onSave = { viewModel.updatePackage(projectId, it) },
            onDismiss = { editingPackage = null }
        )
    }

    deletePackageTarget?.let { pkg ->
        AlertDialog(
            onDismissRequest = { deletePackageTarget = null },
            title = { Text("Delete Package") },
            text = { Text("Are you sure you want to delete \"${pkg.name}\"?") },
            confirmButton = {
                TextButton(
                    onClick = {
                        viewModel.deletePackage(projectId, pkg.id)
                        deletePackageTarget = null
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) { Text("Delete") }
            },
            dismissButton = {
                TextButton(onClick = { deletePackageTarget = null }) { Text("Cancel") }
            }
        )
    }
}

@Composable
private fun ProjectSettingsCard(
    project: ProjectData,
    ipInput: String,
    onIpInputChange: (String) -> Unit,
    portInput: String,
    onPortInputChange: (String) -> Unit,
    projectIps: List<String>,
    isBroadcast: Boolean,
    onBroadcastChange: (Boolean) -> Unit,
    onAddIp: () -> Unit,
    onRemoveIp: (String) -> Unit,
    onApply: () -> Unit,
    ipError: String?
) {
    Card(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    Icons.Default.Settings,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(20.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    "Project Settings",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
            }
            Spacer(modifier = Modifier.height(16.dp))

            // Broadcast toggle
            SwitchListItem(
                title = "Broadcast Mode",
                subtitle = "Send to all devices on network",
                icon = Icons.Default.Sensors,
                checked = isBroadcast,
                onCheckedChange = onBroadcastChange
            )
            Spacer(modifier = Modifier.height(8.dp))

            if (!isBroadcast) {
                Text(
                    "Target IP Addresses",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(8.dp))
                Row(verticalAlignment = Alignment.Top) {
                    OutlinedTextField(
                        value = ipInput,
                        onValueChange = onIpInputChange,
                        label = { Text("IP Address") },
                        placeholder = { Text("192.168.1.100") },
                        leadingIcon = { Icon(Icons.Default.Computer, null) },
                        isError = ipError != null,
                        supportingText = ipError?.let { { Text(it) } },
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Decimal,
                            imeAction = ImeAction.Done
                        ),
                        keyboardActions = KeyboardActions(onDone = { onAddIp() }),
                        modifier = Modifier.weight(1f),
                        singleLine = true
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    FilledIconButton(
                        onClick = onAddIp,
                        modifier = Modifier.padding(top = 4.dp)
                    ) {
                        Icon(Icons.Default.Add, contentDescription = "Add IP")
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                if (projectIps.isNotEmpty()) {
                    IpChipRow(
                        ips = projectIps,
                        onRemove = { ip -> onRemoveIp(ip) },
                        canRemove = true
                    )
                } else {
                    Surface(
                        shape = MaterialTheme.shapes.small,
                        color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Row(
                            modifier = Modifier.padding(10.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.WarningAmber,
                                contentDescription = null,
                                modifier = Modifier.size(16.dp),
                                tint = MaterialTheme.colorScheme.error
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                "No target IPs — add one above before sending",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
            } else {
                Surface(
                    shape = MaterialTheme.shapes.small,
                    color = MaterialTheme.colorScheme.primaryContainer,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Row(modifier = Modifier.padding(12.dp)) {
                        Icon(
                            Icons.Default.Info,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                            tint = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            "Packages will be broadcast to all devices on your local network",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
            }

            Row(verticalAlignment = Alignment.Top) {
                OutlinedTextField(
                    value = portInput,
                    onValueChange = onPortInputChange,
                    label = { Text("UDP Port") },
                    leadingIcon = { Icon(Icons.Default.Router, null) },
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(onDone = { onApply() }),
                    modifier = Modifier.weight(1f),
                    singleLine = true
                )
                Spacer(modifier = Modifier.width(8.dp))
                Button(
                    onClick = onApply,
                    modifier = Modifier.padding(top = 4.dp)
                ) {
                    Icon(Icons.Default.Check, contentDescription = null, modifier = Modifier.size(18.dp))
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("Apply")
                }
            }
        }
    }
}

@Composable
private fun SwitchListItem(
    title: String,
    subtitle: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
        Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
        Spacer(modifier = Modifier.width(16.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(title, style = MaterialTheme.typography.bodyLarge)
            Text(
                subtitle,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        Switch(checked = checked, onCheckedChange = onCheckedChange)
    }
}

@Composable
private fun IpChipRow(ips: List<String>, onRemove: (String) -> Unit, canRemove: Boolean) {
    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        ips.forEach { ip ->
            InputChip(
                selected = false,
                onClick = {},
                label = { Text(ip) },
                trailingIcon = if (canRemove) {
                    {
                        IconButton(
                            onClick = { onRemove(ip) },
                            modifier = Modifier.size(18.dp)
                        ) {
                            Icon(Icons.Default.Close, contentDescription = "Remove", modifier = Modifier.size(14.dp))
                        }
                    }
                } else null
            )
        }
    }
}

@Composable
private fun PackageCard(
    pkg: UdpPackageData,
    project: ProjectData,
    isSending: Boolean,
    wasSent: Boolean,
    onSend: () -> Unit,
    onEdit: () -> Unit,
    onCopy: () -> Unit,
    onDelete: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = if (wasSent) CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        ) else CardDefaults.cardColors()
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(verticalAlignment = Alignment.Top) {
                Column(modifier = Modifier.weight(1f)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(
                            pkg.name,
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.weight(1f)
                        )
                        if (wasSent) {
                            Surface(
                                shape = MaterialTheme.shapes.extraLarge,
                                color = Color(0xFF4CAF50)
                            ) {
                                Row(
                                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Icon(
                                        Icons.Default.Check,
                                        contentDescription = null,
                                        modifier = Modifier.size(14.dp),
                                        tint = Color.White
                                    )
                                    Spacer(modifier = Modifier.width(4.dp))
                                    Text("Sent", color = Color.White, fontSize = 12.sp)
                                }
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                    if (pkg.isBroadcast) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                Icons.Default.Sensors,
                                contentDescription = null,
                                modifier = Modifier.size(14.dp),
                                tint = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text(
                                "Broadcast • Port: ${project.port}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.primary,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    } else {
                        val ipText = if (pkg.ipAddresses.size > 1)
                            "To: ${pkg.ipAddresses.joinToString(", ")} • Port: ${project.port}"
                        else
                            "To: ${pkg.ipAddresses.firstOrNull() ?: ""}:${project.port}"
                        Text(
                            ipText,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 2
                        )
                    }
                }
                var menuExpanded by remember { mutableStateOf(false) }
                Box {
                    IconButton(onClick = { menuExpanded = true }) {
                        Icon(Icons.Default.MoreVert, contentDescription = "Options")
                    }
                    DropdownMenu(
                        expanded = menuExpanded,
                        onDismissRequest = { menuExpanded = false }
                    ) {
                        DropdownMenuItem(
                            text = { Text("Edit") },
                            leadingIcon = { Icon(Icons.Default.Edit, null) },
                            onClick = { menuExpanded = false; onEdit() }
                        )
                        DropdownMenuItem(
                            text = { Text("Copy") },
                            leadingIcon = { Icon(Icons.Default.ContentCopy, null) },
                            onClick = { menuExpanded = false; onCopy() }
                        )
                        DropdownMenuItem(
                            text = { Text("Delete", color = MaterialTheme.colorScheme.error) },
                            leadingIcon = {
                                Icon(Icons.Default.Delete, null, tint = MaterialTheme.colorScheme.error)
                            },
                            onClick = { menuExpanded = false; onDelete() }
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.height(12.dp))
            Surface(
                shape = MaterialTheme.shapes.small,
                color = MaterialTheme.colorScheme.surfaceContainerHighest,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    pkg.data,
                    modifier = Modifier.padding(12.dp),
                    fontFamily = FontFamily.Monospace,
                    fontSize = 12.sp
                )
            }
            Spacer(modifier = Modifier.height(12.dp))
            Button(
                onClick = onSend,
                enabled = !isSending,
                modifier = Modifier.fillMaxWidth()
            ) {
                if (isSending) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Sending...")
                } else {
                    Icon(Icons.Default.Send, contentDescription = null, modifier = Modifier.size(18.dp))
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Send")
                }
            }
        }
    }
}

@Composable
fun PackageDialog(
    pkg: UdpPackageData?,
    projectIps: List<String>,
    onSave: (UdpPackageData) -> Unit,
    onDismiss: () -> Unit
) {
    var name by remember { mutableStateOf(pkg?.name ?: "") }
    var dataText by remember { mutableStateOf(pkg?.data ?: "") }
    var isBroadcast by remember { mutableStateOf(pkg?.isBroadcast ?: false) }
    var ipAddresses by remember {
        mutableStateOf((pkg?.ipAddresses?.takeIf { it.isNotEmpty() } ?: projectIps).toMutableList())
    }
    var ipInput by remember { mutableStateOf("") }

    var nameError by remember { mutableStateOf<String?>(null) }
    var dataError by remember { mutableStateOf<String?>(null) }
    var ipError by remember { mutableStateOf<String?>(null) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(if (pkg == null) "New Package" else "Edit Package") },
        text = {
            Column(
                modifier = Modifier.verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it; nameError = null },
                    label = { Text("Package Name") },
                    leadingIcon = { Icon(Icons.Default.Label, null) },
                    isError = nameError != null,
                    supportingText = nameError?.let { { Text(it) } },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )

                SwitchListItem(
                    title = "Broadcast Mode",
                    subtitle = "Send to all devices",
                    icon = Icons.Default.Sensors,
                    checked = isBroadcast,
                    onCheckedChange = { isBroadcast = it }
                )

                if (!isBroadcast) {
                    Text(
                        "Target IP Addresses",
                        style = MaterialTheme.typography.titleSmall
                    )
                    Row(verticalAlignment = Alignment.Top) {
                        OutlinedTextField(
                            value = ipInput,
                            onValueChange = { ipInput = it; ipError = null },
                            label = { Text("IP Address") },
                            placeholder = { Text("192.168.1.100") },
                            leadingIcon = { Icon(Icons.Default.Computer, null) },
                            isError = ipError != null,
                            supportingText = ipError?.let { { Text(it) } },
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Decimal,
                                imeAction = ImeAction.Done
                            ),
                            keyboardActions = KeyboardActions(onDone = {
                                val ip = ipInput.trim()
                                when {
                                    !isValidIp(ip) -> ipError = "Invalid IP address"
                                    ipAddresses.contains(ip) -> ipError = "Already added"
                                    else -> { ipAddresses = (ipAddresses + ip).toMutableList(); ipInput = "" }
                                }
                            }),
                            modifier = Modifier.weight(1f),
                            singleLine = true
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        FilledIconButton(
                            onClick = {
                                val ip = ipInput.trim()
                                when {
                                    !isValidIp(ip) -> ipError = "Invalid IP address"
                                    ipAddresses.contains(ip) -> ipError = "Already added"
                                    else -> { ipAddresses = (ipAddresses + ip).toMutableList(); ipInput = "" }
                                }
                            },
                            modifier = Modifier.padding(top = 4.dp)
                        ) {
                            Icon(Icons.Default.Add, contentDescription = "Add IP")
                        }
                    }
                    if (ipAddresses.isNotEmpty()) {
                        IpChipRow(
                            ips = ipAddresses,
                            onRemove = { ip ->
                                if (ipAddresses.size > 1) {
                                    ipAddresses = ipAddresses.filter { it != ip }.toMutableList()
                                }
                            },
                            canRemove = ipAddresses.size > 1
                        )
                    }
                } else {
                    Surface(
                        shape = MaterialTheme.shapes.small,
                        color = MaterialTheme.colorScheme.primaryContainer,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Row(modifier = Modifier.padding(12.dp)) {
                            Icon(
                                Icons.Default.Info,
                                contentDescription = null,
                                modifier = Modifier.size(20.dp),
                                tint = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                "This package will be broadcast to all devices on your local network",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                        }
                    }
                }

                OutlinedTextField(
                    value = dataText,
                    onValueChange = { dataText = it; dataError = null },
                    label = { Text("Data") },
                    leadingIcon = { Icon(Icons.Default.DataObject, null) },
                    placeholder = { Text("Enter the data to send") },
                    isError = dataError != null,
                    supportingText = dataError?.let { { Text(it) } },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3,
                    maxLines = 6
                )
            }
        },
        confirmButton = {
            Button(onClick = {
                var valid = true
                if (name.isBlank()) { nameError = "Please enter a package name"; valid = false }
                if (dataText.isEmpty()) { dataError = "Please enter data to send"; valid = false }
                if (valid) {
                    onSave(
                        UdpPackageData(
                            id = pkg?.id ?: System.currentTimeMillis().toString(),
                            name = name.trim(),
                            data = dataText,
                            ipAddresses = if (isBroadcast) emptyList() else ipAddresses.toList(),
                            isBroadcast = isBroadcast
                        )
                    )
                    onDismiss()
                }
            }) { Text("Save") }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text("Cancel") }
        }
    )
}

@Composable
fun BackHandler(onBack: () -> Unit) {
    androidx.activity.compose.BackHandler(onBack = onBack)
}
