package de.krisenvorrat.app.ui.settings

import android.content.Intent
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.krisenvorrat.app.domain.model.AgeGroup
import de.krisenvorrat.app.domain.model.totalDailyKcal

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SettingsScreen(
    viewModel: SettingsViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val context = LocalContext.current

    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument()
    ) { uri ->
        uri?.let { viewModel.onImportFileSelected(it) }
    }

    LaunchedEffect(uiState.shareContent) {
        val content = uiState.shareContent ?: return@LaunchedEffect
        val shareIntent = when (content) {
            is ShareContent.Json -> {
                Intent(Intent.ACTION_SEND).apply {
                    type = "application/json"
                    putExtra(Intent.EXTRA_STREAM, content.fileUri)
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }
            }
            is ShareContent.Markdown -> {
                Intent(Intent.ACTION_SEND).apply {
                    type = "text/plain"
                    putExtra(Intent.EXTRA_TEXT, content.text)
                    putExtra(Intent.EXTRA_SUBJECT, "Krisenvorrat Inventar")
                }
            }
        }
        context.startActivity(Intent.createChooser(shareIntent, "Exportieren via…"))
        viewModel.onShareHandled()
    }

    LaunchedEffect(uiState.exportError) {
        val error = uiState.exportError ?: return@LaunchedEffect
        Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
        viewModel.onExportErrorDismissed()
    }

    Column(modifier = Modifier.fillMaxSize()) {
        TopAppBar(title = { Text("Einstellungen") })

        if (uiState.isLoading) {
            CircularProgressIndicator(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            )
        } else {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp)
            ) {
                Text(
                    text = "Haushalt",
                    style = MaterialTheme.typography.titleMedium
                )

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

                uiState.ageGroups.forEach { entry ->
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text(
                            text = entry.ageGroup.label,
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.weight(1f)
                        )
                        OutlinedTextField(
                            value = entry.count.toString(),
                            onValueChange = { viewModel.onAgeGroupCountChanged(entry.ageGroup, it) },
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            singleLine = true,
                            modifier = Modifier.width(56.dp)
                        )
                        Text("×", style = MaterialTheme.typography.bodyMedium)
                        OutlinedTextField(
                            value = entry.kcalPerDay.toString(),
                            onValueChange = { viewModel.onAgeGroupKcalChanged(entry.ageGroup, it) },
                            label = { Text("kcal/Tag") },
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            singleLine = true,
                            modifier = Modifier.width(104.dp)
                        )
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                }

                val totalKcal = uiState.ageGroups.totalDailyKcal()
                if (totalKcal > 0) {
                    Text(
                        text = "Gesamt: $totalKcal kcal/Tag",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.secondary
                    )
                }

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

                Button(
                    onClick = viewModel::saveSettings,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Speichern")
                }

                if (uiState.isSaved) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "Einstellungen gespeichert",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                }

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

                HorizontalDivider()

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

                Text(
                    text = "Daten",
                    style = MaterialTheme.typography.titleMedium
                )

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

                OutlinedButton(
                    onClick = viewModel::exportJson,
                    enabled = !uiState.isExporting,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Daten exportieren (JSON)")
                }

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

                OutlinedButton(
                    onClick = viewModel::exportMarkdown,
                    enabled = !uiState.isExporting,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Als Markdown teilen")
                }

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

                OutlinedButton(
                    onClick = { filePickerLauncher.launch(arrayOf("application/json")) },
                    enabled = !uiState.isImporting,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Daten importieren")
                }

                if (uiState.isExporting || uiState.isImporting) {
                    Spacer(modifier = Modifier.height(8.dp))
                    CircularProgressIndicator(
                        modifier = Modifier.padding(8.dp)
                    )
                }

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

                HorizontalDivider()

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

                Text(
                    text = "Server-Synchronisierung",
                    style = MaterialTheme.typography.titleMedium
                )

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

                OutlinedTextField(
                    value = uiState.serverUrl,
                    onValueChange = viewModel::onServerUrlChanged,
                    label = { Text("Server-URL") },
                    placeholder = { Text("https://example.com") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )

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

                if (uiState.isLoggedIn) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "Angemeldet als: ${uiState.loggedInUsername}",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.weight(1f)
                        )
                        TextButton(onClick = viewModel::logout) {
                            Text("Abmelden")
                        }
                    }
                } else {
                    OutlinedTextField(
                        value = uiState.loginUsername,
                        onValueChange = viewModel::onLoginUsernameChanged,
                        label = { Text("Benutzername") },
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth()
                    )

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

                    OutlinedTextField(
                        value = uiState.loginPassword,
                        onValueChange = viewModel::onLoginPasswordChanged,
                        label = { Text("Passwort") },
                        visualTransformation = PasswordVisualTransformation(),
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth()
                    )

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

                    Button(
                        onClick = viewModel::login,
                        enabled = !uiState.isLoggingIn,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        if (uiState.isLoggingIn) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(18.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                        }
                        Text("Anmelden")
                    }

                    if (uiState.loginError != null) {
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = uiState.loginError ?: "",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.error
                        )
                    }
                }

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

                val isSyncEnabled = uiState.isLoggedIn &&
                    uiState.serverUrl.isNotBlank() &&
                    uiState.syncStatus !is SyncStatus.Running

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = viewModel::pushSync,
                        enabled = isSyncEnabled,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Push (Hochladen)")
                    }

                    OutlinedButton(
                        onClick = viewModel::pullSync,
                        enabled = isSyncEnabled,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Pull (Herunterladen)")
                    }
                }

                when (val syncStatus = uiState.syncStatus) {
                    is SyncStatus.Running -> {
                        Spacer(modifier = Modifier.height(12.dp))
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            CircularProgressIndicator(modifier = Modifier.size(20.dp))
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Synchronisierung läuft…",
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }
                    is SyncStatus.Success -> {
                        Spacer(modifier = Modifier.height(12.dp))
                        Text(
                            text = "Synchronisierung erfolgreich",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                    is SyncStatus.Error -> {
                        Spacer(modifier = Modifier.height(12.dp))
                        Text(
                            text = syncStatus.message,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.error
                        )
                    }
                    is SyncStatus.Idle -> { /* no indicator */ }
                }

                if (uiState.lastSyncTime != null) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "Letzte Synchronisierung: ${uiState.lastSyncTime}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                if (de.krisenvorrat.app.BuildConfig.FEATURE_CAMERA_ENABLED) {
                    Spacer(modifier = Modifier.height(32.dp))

                    HorizontalDivider()

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

                    Text(
                        text = "KI-Erkennung",
                        style = MaterialTheme.typography.titleMedium
                    )

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

                    OutlinedTextField(
                        value = uiState.openAiApiKey,
                        onValueChange = viewModel::onOpenAiApiKeyChanged,
                        label = { Text("OpenAI API-Key") },
                        visualTransformation = PasswordVisualTransformation(),
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth()
                    )

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

                    Text(
                        text = "Wird für die KI-gestützte Foto-Erkennung benötigt.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.secondary
                    )
                }
            }
        }
    }

    if (uiState.pendingImportUri != null) {
        AlertDialog(
            onDismissRequest = viewModel::onImportDismissed,
            title = { Text("Daten importieren?") },
            text = { Text("Bestehende Daten werden durch den Import überschrieben. Möchten Sie fortfahren?") },
            confirmButton = {
                TextButton(onClick = viewModel::onImportConfirmed) {
                    Text("Importieren")
                }
            },
            dismissButton = {
                TextButton(onClick = viewModel::onImportDismissed) {
                    Text("Abbrechen")
                }
            }
        )
    }

    val importResult = uiState.importResult
    if (importResult != null) {
        AlertDialog(
            onDismissRequest = viewModel::onImportResultDismissed,
            title = {
                Text(
                    when (importResult) {
                        is ImportResult.Success -> "Import erfolgreich"
                        is ImportResult.Error -> "Import fehlgeschlagen"
                    }
                )
            },
            text = {
                Text(
                    when (importResult) {
                        is ImportResult.Success -> "Daten wurden erfolgreich importiert."
                        is ImportResult.Error -> importResult.message
                    }
                )
            },
            confirmButton = {
                TextButton(onClick = viewModel::onImportResultDismissed) {
                    Text("OK")
                }
            }
        )
    }
}

