package com.example.todokmp.android.ui

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.example.todokmp.android.TodoViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoApp(viewModel: TodoViewModel) {
    val filteredTodos by viewModel.filteredTodos.collectAsState()
    val currentFilter by viewModel.filter.collectAsState()
    val counts by viewModel.counts.collectAsState()
    val showForm by viewModel.showForm.collectAsState()
    val editingTodo by viewModel.editingTodo.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Todos – Kotlin KMP") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = MaterialTheme.colorScheme.onPrimary
                )
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { viewModel.showAddForm() }) {
                Icon(Icons.Default.Add, contentDescription = "Add todo")
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier.padding(innerPadding)
        ) {
            FilterBar(
                currentFilter = currentFilter,
                counts = counts,
                onFilterSelected = { viewModel.setFilter(it) }
            )

            TodoList(
                todos = filteredTodos,
                onToggle = { viewModel.toggleTodo(it) },
                onEdit = { viewModel.showEditForm(it) },
                onDelete = { viewModel.deleteTodo(it) },
                modifier = Modifier.weight(1f)
            )
        }
    }

    if (showForm) {
        TodoFormDialog(
            editingTodo = editingTodo,
            onDismiss = { viewModel.dismissForm() },
            onSave = { title, category, priority ->
                val editing = editingTodo
                if (editing != null) {
                    viewModel.updateTodo(editing.id, title, category, priority)
                } else {
                    viewModel.addTodo(title, category, priority)
                }
            }
        )
    }
}
