package com.example.todokmp.android.ui

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.todokmp.db.TodoEntity

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoList(
    todos: List<TodoEntity>,
    onToggle: (TodoEntity) -> Unit,
    onEdit: (TodoEntity) -> Unit,
    onDelete: (TodoEntity) -> Unit,
    modifier: Modifier = Modifier
) {
    if (todos.isEmpty()) {
        EmptyState(modifier = modifier)
    } else {
        LazyColumn(modifier = modifier.fillMaxSize()) {
            items(items = todos, key = { it.id }) { todo ->
                val dismissState = rememberSwipeToDismissBoxState(
                    confirmValueChange = { value ->
                        if (value == SwipeToDismissBoxValue.EndToStart) {
                            onDelete(todo)
                            true
                        } else {
                            false
                        }
                    }
                )

                SwipeToDismissBox(
                    state = dismissState,
                    backgroundContent = {
                        SwipeToDismissBackground(color = MaterialTheme.colorScheme.error)
                    },
                    enableDismissFromStartToEnd = false,
                    enableDismissFromEndToStart = true
                ) {
                    TodoItem(
                        todo = todo,
                        onToggle = { onToggle(todo) },
                        onClick = { onEdit(todo) }
                    )
                }
            }
        }
    }
}

@Composable
private fun SwipeToDismissBackground(color: Color) {
    Surface(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp, vertical = 4.dp),
        color = color,
        shape = CardDefaults.shape
    ) {}
}
