package de.haushalt.app.ui.task

import androidx.compose.foundation.clickable
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.DateRange
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.AlertDialog
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.material3.TextButton
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.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import de.haushalt.app.data.Task
import de.haushalt.app.data.TaskStatus

@Composable
fun TaskAllScreen(
    navController: NavController,
    viewModel: TaskAllViewModel = viewModel(),
) {
    var deleteCandidate by remember { mutableStateOf<Int?>(null) }

    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") }) {
                Icon(Icons.Filled.DateRange, contentDescription = "Schemas")
            }
            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.tasks.isEmpty() -> Text("Lädt…")
            viewModel.error != null -> Text(
                viewModel.error ?: "",
                color = MaterialTheme.colorScheme.error
            )
            viewModel.tasks.isEmpty() -> Text("Keine Tasks.")
            else -> LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(viewModel.tasks, key = { it.id ?: 0 }) { task ->
                    TaskAllRow(
                        task = task,
                        onClick = { task.id?.let(viewModel::toggle) },
                        onEdit = { task.id?.let { navController.navigate("tasks/$it") } },
                        onDelete = { deleteCandidate = task.id },
                    )
                    HorizontalDivider()
                }
            }
        }
    }

    if (deleteCandidate != null) {
        AlertDialog(
            onDismissRequest = { deleteCandidate = null },
            title = { Text("Task löschen?") },
            text = { Text("Dieser Task wird dauerhaft entfernt.") },
            confirmButton = {
                TextButton(onClick = {
                    deleteCandidate?.let(viewModel::delete)
                    deleteCandidate = null
                }) { Text("Löschen") }
            },
            dismissButton = {
                TextButton(onClick = { deleteCandidate = null }) { Text("Abbrechen") }
            },
        )
    }
}

@Composable
private fun TaskAllRow(
    task: Task,
    onClick: () -> Unit,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .alpha(if (task.status == TaskStatus.past) 0.5f else 1f)
            .clickable(onClick = onClick)
            .padding(vertical = 8.dp, horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = task.name,
            style = MaterialTheme.typography.bodyLarge,
            textDecoration = if (task.status == TaskStatus.done) TextDecoration.LineThrough else null,
            fontStyle = if (task.status == TaskStatus.inactive) FontStyle.Italic else null,
            color = when (task.status) {
                TaskStatus.active -> MaterialTheme.colorScheme.onSurface
                TaskStatus.done -> MaterialTheme.colorScheme.onSurfaceVariant
                TaskStatus.inactive -> MaterialTheme.colorScheme.onSurfaceVariant
                TaskStatus.past -> MaterialTheme.colorScheme.onSurfaceVariant
            },
            modifier = Modifier.weight(1f),
        )
        task.date?.let {
            Text(
                text = formatDate(it),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(end = 8.dp),
            )
        }
        IconButton(onClick = onEdit) {
            Icon(Icons.Filled.Edit, contentDescription = "Bearbeiten")
        }
        IconButton(onClick = onDelete) {
            Icon(Icons.Filled.Delete, contentDescription = "Löschen")
        }
    }
}
