package de.haushalt.app

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import de.haushalt.app.data.AppUpdater
import de.haushalt.app.data.AppVersion
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

private sealed interface UpdateState {
    data object Idle : UpdateState
    data object Checking : UpdateState
    data object NoUpdate : UpdateState
    data class Available(val version: AppVersion) : UpdateState
    data object Downloading : UpdateState
    data class Error(val message: String) : UpdateState
}

@Composable
fun StartScreen(onOpenTasks: () -> Unit = {}) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var updateState by remember { mutableStateOf<UpdateState>(UpdateState.Idle) }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        LazyVerticalGrid(
            columns = GridCells.Adaptive(minSize = 160.dp),
            modifier = Modifier.weight(1f),
        ) {
            item {
                Card(
                    onClick = onOpenTasks,
                    modifier = Modifier
                        .padding(8.dp)
                        .aspectRatio(1f),
                ) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text(
                            text = "Tasks",
                            style = MaterialTheme.typography.titleLarge,
                        )
                    }
                }
            }
        }

        Spacer(Modifier.padding(8.dp))

        Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
            when (val state = updateState) {
                UpdateState.Idle -> TextButton(onClick = {
                    scope.launch {
                        updateState = UpdateState.Checking
                        try {
                            val version = withContext(Dispatchers.IO) { AppUpdater.checkUpdate() }
                            updateState = if (version != null) UpdateState.Available(version)
                            else UpdateState.NoUpdate
                        } catch (e: Exception) {
                            updateState = UpdateState.Error(e.message ?: "Fehler")
                        }
                    }
                }) { Text("Update prüfen") }

                UpdateState.Checking -> Text("Prüfe…", style = MaterialTheme.typography.bodySmall)

                UpdateState.NoUpdate -> Text(
                    "App ist aktuell",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )

                is UpdateState.Available -> Button(onClick = {
                    scope.launch {
                        updateState = UpdateState.Downloading
                        try {
                            withContext(Dispatchers.IO) {
                                AppUpdater.downloadAndInstall(context, state.version)
                            }
                            updateState = UpdateState.Idle
                        } catch (e: Exception) {
                            updateState = UpdateState.Error(e.message ?: "Fehler")
                        }
                    }
                }) { Text("Update installieren (v${state.version.versionCode})") }

                UpdateState.Downloading -> Text(
                    "Lade herunter…",
                    style = MaterialTheme.typography.bodySmall,
                )

                is UpdateState.Error -> TextButton(onClick = { updateState = UpdateState.Idle }) {
                    Text(state.message, color = MaterialTheme.colorScheme.error)
                }
            }
        }
    }
}
