package de.haushalt.app.ui.schema

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.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import de.haushalt.app.data.TaskSchema
import de.haushalt.app.data.TaskSchemaStatus

@Composable
fun SchemaAllScreen(
    navController: NavController,
    viewModel: SchemaAllViewModel = viewModel(),
) {
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) {
                viewModel.refresh()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
    }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End,
        ) {
            IconButton(onClick = { navController.navigate("schemas/create") }) {
                Icon(Icons.Filled.Add, contentDescription = "Neues Schema")
            }
            IconButton(onClick = { viewModel.refresh() }) {
                Icon(Icons.Filled.Refresh, contentDescription = "Neu laden")
            }
        }

        Spacer(Modifier.padding(4.dp))

        when {
            viewModel.isLoading && viewModel.schemas.isEmpty() -> Text("Lädt…")
            viewModel.error != null -> Text(viewModel.error ?: "", color = MaterialTheme.colorScheme.error)
            viewModel.schemas.isEmpty() -> Text("Keine Schemas.")
            else -> LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(viewModel.schemas, key = { it.id ?: 0 }) { schema ->
                    SchemaRow(
                        schema = schema,
                        onEdit = { schema.id?.let { navController.navigate("schemas/$it") } },
                        onDelete = { schema.id?.let(viewModel::delete) },
                    )
                    HorizontalDivider()
                }
            }
        }
    }
}

@Composable
private fun SchemaRow(
    schema: TaskSchema,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
) {
    val repeatLabel = when {
        schema.repeat == null -> "Einmalig"
        schema.repeat.containsKey("daily") -> "Täglich"
        schema.repeat.containsKey("weekly") -> "Wöchentlich"
        schema.repeat.containsKey("2week") -> "2-Wöchentlich"
        schema.repeat.containsKey("4week") -> "4-Wöchentlich"
        schema.repeat.containsKey("monthly") -> "Monatlich"
        schema.repeat.containsKey("days") -> "Mehrere Tage"
        else -> ""
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .alpha(if (schema.status == TaskSchemaStatus.inactive) 0.5f else 1f)
            .padding(vertical = 8.dp, horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Row(
            modifier = Modifier.weight(1f),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = schema.name,
                style = MaterialTheme.typography.bodyLarge,
                fontStyle = if (schema.status == TaskSchemaStatus.inactive) FontStyle.Italic else null,
            )
            Text(
                text = repeatLabel,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
        IconButton(onClick = onEdit) {
            Icon(Icons.Filled.Edit, contentDescription = "Bearbeiten")
        }
        IconButton(onClick = onDelete) {
            Icon(Icons.Filled.Delete, contentDescription = "Löschen")
        }
    }
}
