package de.haushalt.app.ui.task

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLifecycleOwner
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 TaskScreen(
    navController: NavController,
    viewModel: TaskListViewModel = viewModel(),
) {
    val tasks = viewModel.visibleTasks
    val showDone by androidx.compose.runtime.rememberUpdatedState(viewModel.showDone)

    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 = { navController.navigate("tasks/all") }) {
                Icon(Icons.AutoMirrored.Filled.List, contentDescription = "Alle Tasks")
            }
            IconButton(onClick = { viewModel.toggleShowDone() }) {
                Icon(
                    imageVector = if (showDone) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
                    contentDescription = "Erledigte ein-/ausblenden",
                )
            }
            IconButton(onClick = { viewModel.refresh() }) {
                Icon(Icons.Filled.Refresh, contentDescription = "Neu laden")
            }
        }

        Spacer(Modifier.padding(4.dp))

        when {
            viewModel.isLoading && tasks.isEmpty() -> Text("Lädt…")
            viewModel.error != null -> Text(viewModel.error ?: "", color = MaterialTheme.colorScheme.error)
            tasks.isEmpty() -> Text("Keine Tasks.")
            else -> LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(top = 12.dp, bottom = 12.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
            ) {
                viewModel.groupedTasks.forEach { (key, groupTasks) ->
                    item(key = key.ifEmpty { "no-date" }) {
                        TaskGroupCard(
                            title = key.ifEmpty { null },
                            tasks = groupTasks,
                            onToggle = viewModel::toggle,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun TaskRow(task: Task, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp, horizontal = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = task.name,
            style = MaterialTheme.typography.bodyLarge,
            textDecoration = if (task.status == TaskStatus.done) TextDecoration.LineThrough else null,
            color = if (task.status == TaskStatus.done) MaterialTheme.colorScheme.onSurfaceVariant
            else MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.weight(1f),
        )
    }
}

@Composable
private fun TaskGroupCard(
    title: String?,
    tasks: List<Task>,
    onToggle: (Int) -> Unit,
) {
    Box(modifier = Modifier.fillMaxWidth()) {
        OutlinedCard(modifier = Modifier.fillMaxWidth()) {
            Column {
                tasks.forEachIndexed { index, task ->
                    TaskRow(task = task, onClick = { task.id?.let(onToggle) })
                    if (index < tasks.lastIndex) HorizontalDivider()
                }
            }
        }
        if (title != null) {
            Surface(
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .offset(y = (-10).dp),
                shape = RoundedCornerShape(6.dp),
                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
                color = MaterialTheme.colorScheme.background,
            ) {
                Text(
                    text = title,
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
    }
}
