package com.atridad.ascently.ui.screens

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.atridad.ascently.R
import com.atridad.ascently.ui.components.SyncIndicator
import com.atridad.ascently.ui.health.HealthConnectCard
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
import kotlinx.coroutines.launch
import java.io.File
import java.time.Instant

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(viewModel: ClimbViewModel) {
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    // Sync service state
    val syncService = viewModel.syncService
    val isSyncing by syncService.isSyncing.collectAsState()
    val isConnected by syncService.isConnected.collectAsState()
    val isConfigured by syncService.isConfiguredFlow.collectAsState()
    val isTesting by syncService.isTesting.collectAsState()
    val lastSyncTime by syncService.lastSyncTime.collectAsState()
    val syncError by syncService.syncError.collectAsState()
    val isAutoSyncEnabled by syncService.isAutoSyncEnabled.collectAsState()

    // State for dialogs
    var showResetDialog by remember { mutableStateOf(false) }
    var showSyncConfigDialog by remember { mutableStateOf(false) }
    var showDisconnectDialog by remember { mutableStateOf(false) }

    var showDeleteImagesDialog by remember { mutableStateOf(false) }

    var isDeletingImages by remember { mutableStateOf(false) }

    // Sync configuration state
    var serverUrl by remember { mutableStateOf(syncService.serverUrl) }
    var authToken by remember { mutableStateOf(syncService.authToken) }

    val packageInfo = remember { context.packageManager.getPackageInfo(context.packageName, 0) }
    val appVersion = packageInfo.versionName

    // Update local state when sync service configuration changes
    LaunchedEffect(syncService.serverUrl, syncService.authToken) {
        serverUrl = syncService.serverUrl
        authToken = syncService.authToken
    }

    // File picker launcher for import - only accepts ZIP files
    val importLauncher =
        rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri,
            ->
            uri?.let {
                try {
                    val inputStream = context.contentResolver.openInputStream(uri)
                    // Determine file extension from content resolver
                    val fileName =
                        context.contentResolver.query(uri, null, null, null, null)?.use {
                                cursor ->
                            val nameIndex =
                                cursor.getColumnIndex(
                                    android.provider.OpenableColumns.DISPLAY_NAME,
                                )
                            if (nameIndex >= 0 && cursor.moveToFirst()) {
                                cursor.getString(nameIndex)
                            } else {
                                null
                            }
                        }
                            ?: "import_file"

                    // Only allow ZIP files
                    if (!fileName.lowercase().endsWith(".zip")) {
                        viewModel.setError(
                            "Only ZIP files are supported for import. Please use a ZIP file exported from Ascently.",
                        )
                        return@let
                    }

                    val tempFile = File(context.cacheDir, "temp_import.zip")

                    inputStream?.use { input ->
                        tempFile.outputStream().use { output -> input.copyTo(output) }
                    }
                    viewModel.importData(tempFile)
                } catch (e: Exception) {
                    viewModel.setError("Failed to read file: ${e.message}")
                }
            }
        }

    // File picker launcher for export - ZIP format with images
    val exportZipLauncher =
        rememberLauncherForActivityResult(
            contract = ActivityResultContracts.CreateDocument("application/zip"),
        ) { uri ->
            uri?.let {
                try {
                    viewModel.exportDataToZipUri(context, uri)
                } catch (e: Exception) {
                    viewModel.setError("Failed to save file: ${e.message}")
                }
            }
        }

    LazyColumn(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.ic_mountains),
                    contentDescription = "Ascently Logo",
                    modifier = Modifier.size(32.dp),
                    tint = MaterialTheme.colorScheme.primary,
                )
                Text(
                    text = "Settings",
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                )
                SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
            }
        }

        // Sync Section
        item {
            Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
                Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
                    Text(
                        text = "Sync",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                    )

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

                    if (isConfigured) {
                        // Connected state
                        Card(
                            shape = RoundedCornerShape(12.dp),
                            colors =
                            CardDefaults.cardColors(
                                containerColor =
                                if (isConnected) {
                                    MaterialTheme.colorScheme
                                        .primaryContainer.copy(
                                            alpha = 0.3f,
                                        )
                                } else {
                                    MaterialTheme.colorScheme
                                        .surfaceVariant.copy(
                                            alpha = 0.3f,
                                        )
                                },
                            ),
                        ) {
                            ListItem(
                                headlineContent = {
                                    Text(
                                        if (isConnected) {
                                            "Connected to Server"
                                        } else {
                                            "Server Configured"
                                        },
                                    )
                                },
                                supportingContent = {
                                    Column {
                                        Text("Server: ${syncService.serverUrl}")
                                        lastSyncTime?.let { time ->
                                            Text(
                                                "Last sync: ${
                                                    try {
                                                        Instant.parse(time).toString()
                                                    } catch (_: Exception) {
                                                        time
                                                    }
                                                }",
                                                style = MaterialTheme.typography.bodySmall,
                                            )
                                        }
                                    }
                                },
                                leadingContent = {
                                    Icon(
                                        if (isConnected) {
                                            Icons.Default.CloudDone
                                        } else {
                                            Icons.Default.Cloud
                                        },
                                        contentDescription = null,
                                        tint =
                                        if (isConnected) {
                                            MaterialTheme.colorScheme.primary
                                        } else {
                                            MaterialTheme.colorScheme
                                                .onSurfaceVariant
                                        },
                                    )
                                },
                                trailingContent = {
                                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                        // Manual Sync Button
                                        TextButton(
                                            onClick = {
                                                viewModel.performManualSync()
                                            },
                                            enabled = isConnected && !isSyncing,
                                        ) {
                                            if (isSyncing) {
                                                CircularProgressIndicator(
                                                    modifier = Modifier.size(16.dp),
                                                    strokeWidth = 2.dp,
                                                )
                                            } else {
                                                Text("Sync")
                                            }
                                        }

                                        // Configure Button
                                        TextButton(onClick = { showSyncConfigDialog = true }) {
                                            Text("Configure")
                                        }
                                    }
                                },
                            )
                        }

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

                        // Auto-sync settings
                        Card(
                            shape = RoundedCornerShape(12.dp),
                            colors =
                            CardDefaults.cardColors(
                                containerColor =
                                MaterialTheme.colorScheme.surfaceVariant
                                    .copy(alpha = 0.3f),
                            ),
                        ) {
                            Column(modifier = Modifier.padding(16.dp)) {
                                Text(
                                    text = "Sync Mode",
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.Medium,
                                )

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

                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text("Auto-sync")
                                        Text(
                                            text =
                                            "Sync automatically on app launch and data changes",
                                            style = MaterialTheme.typography.bodySmall,
                                            color =
                                            MaterialTheme.colorScheme.onSurface.copy(
                                                alpha = 0.7f,
                                            ),
                                            maxLines = 2,
                                        )
                                    }
                                    Spacer(modifier = Modifier.width(16.dp))
                                    Switch(
                                        checked = isAutoSyncEnabled,
                                        onCheckedChange = { enabled ->
                                            syncService.setAutoSyncEnabled(enabled)
                                        },
                                    )
                                }
                            }
                        }

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

                        // Disconnect option
                        Card(
                            shape = RoundedCornerShape(12.dp),
                            colors =
                            CardDefaults.cardColors(
                                containerColor =
                                MaterialTheme.colorScheme.errorContainer
                                    .copy(alpha = 0.3f),
                            ),
                        ) {
                            ListItem(
                                headlineContent = { Text("Disconnect") },
                                supportingContent = { Text("Clear sync configuration") },
                                leadingContent = {
                                    Icon(
                                        Icons.Default.CloudOff,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.error,
                                    )
                                },
                                trailingContent = {
                                    TextButton(onClick = { showDisconnectDialog = true }) {
                                        Text(
                                            "Disconnect",
                                            color = MaterialTheme.colorScheme.error,
                                        )
                                    }
                                },
                            )
                        }
                    } else {
                        // Not configured state
                        Card(
                            shape = RoundedCornerShape(12.dp),
                            colors =
                            CardDefaults.cardColors(
                                containerColor =
                                MaterialTheme.colorScheme.surfaceVariant
                                    .copy(alpha = 0.3f),
                            ),
                        ) {
                            ListItem(
                                headlineContent = { Text("Setup Sync") },
                                supportingContent = {
                                    Text("Connect to your Ascently sync server")
                                },
                                leadingContent = {
                                    Icon(Icons.Default.CloudSync, contentDescription = null)
                                },
                                trailingContent = {
                                    TextButton(onClick = { showSyncConfigDialog = true }) {
                                        Text("Setup")
                                    }
                                },
                            )
                        }
                    }

                    // Show sync error if any
                    syncError?.let { error ->
                        Spacer(modifier = Modifier.height(8.dp))
                        Card(
                            shape = RoundedCornerShape(12.dp),
                            colors =
                            CardDefaults.cardColors(
                                containerColor =
                                MaterialTheme.colorScheme.errorContainer,
                            ),
                        ) {
                            Row(
                                modifier = Modifier.fillMaxWidth().padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                Icon(
                                    Icons.Default.Warning,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.error,
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = error,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onErrorContainer,
                                )
                            }
                        }
                    }
                }
            }
        }

        item { HealthConnectCard() }

        item {
            Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
                Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
                    Text(
                        text = "Data Management",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                    )

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

                    // Export Data
                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.surfaceVariant.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        ListItem(
                            headlineContent = { Text("Export Data with Images") },
                            supportingContent = {
                                Text(
                                    "Export all your climbing data and images to ZIP file (recommended)",
                                )
                            },
                            leadingContent = {
                                Icon(Icons.Default.Share, contentDescription = null)
                            },
                            trailingContent = {
                                TextButton(
                                    onClick = {
                                        val defaultFileName =
                                            "ascently_export_${
                                                java.time.LocalDateTime.now()
                                                    .toString()
                                                    .replace(":", "-")
                                                    .replace(".", "-")
                                            }.zip"
                                        exportZipLauncher.launch(defaultFileName)
                                    },
                                    enabled = !uiState.isLoading,
                                ) {
                                    if (uiState.isLoading) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(16.dp),
                                            strokeWidth = 2.dp,
                                        )
                                    } else {
                                        Text("Export ZIP")
                                    }
                                }
                            },
                        )
                    }

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

                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.surfaceVariant.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        ListItem(
                            headlineContent = { Text("Import Data") },
                            supportingContent = {
                                Text("Import climbing data from ZIP file (recommended format)")
                            },
                            leadingContent = {
                                Icon(Icons.Default.Add, contentDescription = null)
                            },
                            trailingContent = {
                                TextButton(
                                    onClick = { importLauncher.launch("application/zip") },
                                    enabled = !uiState.isLoading,
                                ) {
                                    if (uiState.isLoading) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(16.dp),
                                            strokeWidth = 2.dp,
                                        )
                                    } else {
                                        Text("Import")
                                    }
                                }
                            },
                        )
                    }

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

                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.errorContainer.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        ListItem(
                            headlineContent = { Text("Delete All Images") },
                            supportingContent = {
                                Text("Permanently delete all image files from device")
                            },
                            leadingContent = {
                                Icon(
                                    Icons.Default.Delete,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.error,
                                )
                            },
                            trailingContent = {
                                TextButton(
                                    onClick = { showDeleteImagesDialog = true },
                                    enabled = !isDeletingImages && !uiState.isLoading,
                                ) {
                                    if (isDeletingImages) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(16.dp),
                                            strokeWidth = 2.dp,
                                        )
                                    } else {
                                        Text("Delete", color = MaterialTheme.colorScheme.error)
                                    }
                                }
                            },
                        )
                    }

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

                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.errorContainer.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        ListItem(
                            headlineContent = { Text("Reset All Data") },
                            supportingContent = {
                                Text(
                                    "Permanently delete all gyms, problems, sessions, attempts, and images",
                                )
                            },
                            leadingContent = {
                                Icon(
                                    Icons.Default.Delete,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.error,
                                )
                            },
                            trailingContent = {
                                TextButton(
                                    onClick = { showResetDialog = true },
                                    enabled = !uiState.isLoading,
                                ) {
                                    if (uiState.isLoading) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(16.dp),
                                            strokeWidth = 2.dp,
                                        )
                                    } else {
                                        Text("Reset", color = MaterialTheme.colorScheme.error)
                                    }
                                }
                            },
                        )
                    }
                }
            }
        }

        // App Information Section
        item {
            Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
                Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
                    Text(
                        text = "App Information",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                    )

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

                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.surfaceVariant.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        ListItem(
                            headlineContent = { Text("Version") },
                            supportingContent = { Text(appVersion ?: "Unknown") },
                            leadingContent = {
                                Icon(Icons.Default.Info, contentDescription = null)
                            },
                        )
                    }
                }
            }
        }
    }

    // Show loading/message states
    if (uiState.isLoading) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
    }

    uiState.message?.let { message ->
        LaunchedEffect(message) {
            kotlinx.coroutines.delay(5000)
            viewModel.clearMessage()
        }

        Card(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            colors =
            CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
            ),
            shape = RoundedCornerShape(12.dp),
        ) {
            Row(
                modifier = Modifier.fillMaxWidth().padding(16.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    Icons.Default.CheckCircle,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = message,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                )
            }
        }
    }

    uiState.error?.let { error ->
        LaunchedEffect(error) {
            kotlinx.coroutines.delay(5000)
            viewModel.clearError()
        }

        Card(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            colors =
            CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.errorContainer,
            ),
            shape = RoundedCornerShape(12.dp),
        ) {
            Row(
                modifier = Modifier.fillMaxWidth().padding(16.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    Icons.Default.Warning,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.error,
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = error,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onErrorContainer,
                )
            }
        }
    }

    // Reset confirmation dialog
    if (showResetDialog) {
        AlertDialog(
            onDismissRequest = { showResetDialog = false },
            title = { Text("Reset All Data") },
            text = {
                Column {
                    Text("Are you sure you want to reset all data?")
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "This will permanently delete:",
                        style = MaterialTheme.typography.bodySmall,
                        fontWeight = FontWeight.Medium,
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text =
                        "• All gyms and their information\n• All problems and their images\n• All climbing sessions\n• All attempts and progress data",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error,
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text =
                        "This action cannot be undone. Consider exporting your data first.",
                        style = MaterialTheme.typography.bodySmall,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.error,
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        viewModel.resetAllData()
                        showResetDialog = false
                    },
                ) { Text("Reset All Data", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton = {
                TextButton(onClick = { showResetDialog = false }) { Text("Cancel") }
            },
        )
    }

    // Sync Configuration Dialog
    if (showSyncConfigDialog) {
        AlertDialog(
            onDismissRequest = { showSyncConfigDialog = false },
            title = { Text("Sync Configuration") },
            text = {
                Column {
                    OutlinedTextField(
                        value = serverUrl,
                        onValueChange = { serverUrl = it },
                        label = { Text("Server URL") },
                        placeholder = { Text("https://your-server.com") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                    )

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

                    OutlinedTextField(
                        value = authToken,
                        onValueChange = { authToken = it },
                        label = { Text("Auth Token") },
                        placeholder = { Text("your-secret-token") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                    )

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

                    // Connection status indicator
                    if (isTesting) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.fillMaxWidth(),
                        ) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Testing connection...",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.primary,
                            )
                        }
                    } else if (isConnected && isConfigured) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.fillMaxWidth(),
                        ) {
                            Icon(
                                Icons.Default.CheckCircle,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(16.dp),
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Connection successful",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.primary,
                            )
                        }
                    } else if (syncError != null && isConfigured) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.fillMaxWidth(),
                        ) {
                            Icon(
                                Icons.Default.Error,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error,
                                modifier = Modifier.size(16.dp),
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Connection failed: $syncError",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.error,
                            )
                        }
                    } else if (isConfigured) {
                        Text(
                            text = "Test connection before enabling sync features",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    } else {
                        Text(
                            text = "Enter your server URL and auth token to enable sync",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }
            },
            confirmButton = {
                Row {
                    // Primary action: Save & Test
                    Button(
                        onClick = {
                            coroutineScope.launch {
                                try {
                                    syncService.serverUrl = serverUrl.trim()
                                    syncService.authToken = authToken.trim()
                                    viewModel.testSyncConnection()
                                    while (syncService.isTesting.value) {
                                        kotlinx.coroutines.delay(100)
                                    }
                                    showSyncConfigDialog = false
                                } catch (e: Exception) {
                                    viewModel.setError(
                                        "Failed to save and test: ${e.message}",
                                    )
                                }
                            }
                        },
                        enabled =
                        !isTesting &&
                            serverUrl.isNotBlank() &&
                            authToken.isNotBlank(),
                    ) {
                        if (isTesting) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(16.dp),
                                    strokeWidth = 2.dp,
                                    color = MaterialTheme.colorScheme.onPrimary,
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text("Save & Test")
                            }
                        } else {
                            Text("Save & Test")
                        }
                    }

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

                    // Secondary action: Test only (when already configured)
                    if (isConfigured) {
                        TextButton(
                            onClick = {
                                coroutineScope.launch {
                                    try {
                                        syncService.serverUrl = serverUrl.trim()
                                        syncService.authToken = authToken.trim()
                                        viewModel.testSyncConnection()
                                        while (syncService.isTesting.value) {
                                            kotlinx.coroutines.delay(100)
                                        }
                                        if (isConnected) {
                                            showSyncConfigDialog = false
                                        }
                                    } catch (e: Exception) {
                                        viewModel.setError(
                                            "Connection test failed: ${e.message}",
                                        )
                                    }
                                }
                            },
                            enabled =
                            !isTesting &&
                                serverUrl.isNotBlank() &&
                                authToken.isNotBlank(),
                        ) { Text("Test Only") }
                    }
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        serverUrl = syncService.serverUrl
                        authToken = syncService.authToken
                        showSyncConfigDialog = false
                    },
                ) { Text("Cancel") }
            },
        )
    }

    // Disconnect Dialog
    if (showDisconnectDialog) {
        AlertDialog(
            onDismissRequest = { showDisconnectDialog = false },
            title = { Text("Disconnect from Sync") },
            text = {
                Text(
                    "Are you sure you want to disconnect from the sync server? This will clear your server configuration and disable auto-sync.",
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        viewModel.syncService.clearConfiguration()
                        showDisconnectDialog = false
                    },
                ) { Text("Disconnect") }
            },
            dismissButton = {
                TextButton(onClick = { showDisconnectDialog = false }) { Text("Cancel") }
            },
        )
    }

    // Delete All Images dialog
    if (showDeleteImagesDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteImagesDialog = false },
            title = { Text("Delete All Images") },
            text = {
                Text(
                    "This will permanently delete ALL image files from your device." +
                        "\n\nProblems will keep their references but the actual image files " +
                        "will be removed. This cannot be undone." +
                        "\n\nConsider exporting your data first if you want to keep your images.",
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        isDeletingImages = true
                        showDeleteImagesDialog = false
                        coroutineScope.launch {
                            viewModel.deleteAllImages()
                            isDeletingImages = false
                            viewModel.setMessage("All images deleted successfully!")
                        }
                    },
                ) { Text("Delete", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteImagesDialog = false }) { Text("Cancel") }
            },
        )
    }
}
