package com.example.todokmp.android.ui

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.todokmp.db.TodoEntity
import com.example.todokmp.model.Priority

@Composable
fun TodoFormDialog(
    editingTodo: TodoEntity?,
    onDismiss: () -> Unit,
    onSave: (title: String, category: String, priority: Priority) -> Unit
) {
    var title by remember(editingTodo) {
        mutableStateOf(editingTodo?.title ?: "")
    }
    var category by remember(editingTodo) {
        mutableStateOf(editingTodo?.category ?: "Personal")
    }
    var priority by remember(editingTodo) {
        mutableStateOf(
            editingTodo?.let { Priority.fromString(it.priority) } ?: Priority.MEDIUM
        )
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(if (editingTodo != null) "Edit Todo" else "Add Todo")
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
                OutlinedTextField(
                    value = title,
                    onValueChange = { title = it },
                    label = { Text("Title") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )

                Text("Category", style = MaterialTheme.typography.labelLarge)
                CategoryPicker(
                    selected = category,
                    onCategorySelected = { category = it }
                )

                Text("Priority", style = MaterialTheme.typography.labelLarge)
                PriorityPicker(
                    selected = priority,
                    onPrioritySelected = { priority = it }
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = { onSave(title.trim(), category, priority) },
                enabled = title.isNotBlank()
            ) {
                Text("Save")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}
